出于統計分析目的,我想根據它們的值重新組合資料框中的一些行。
是)我有的:
| 數字 | 緯度 |
|---|---|
| 30 | 57 |
| 12 | 59 |
| 01 | 68 |
| 12 | 66 |
| 101 | 55 |
| 47 | 61 |
| 05 | 60 |
| 288 | 67 |
例如,所需的輸出將是在單個類別 66 中重新組合高于 66 (66 67 68) 的每個緯度,所需的輸出將如下所示:
| 數字 | 緯度 | 新的 |
|---|---|---|
| 30 | 57 | 57 |
| 12 | 59 | 59 |
| 01 | 68 | 66 |
| 12 | 66 | 66 |
| 101 | 55 | 55 |
| 47 | 61 | 61 |
| 05 | 60 | 60 |
| 288 | 67 | 66 |
我不想使用 if 回圈,因為我覺得它不是真正的 R 友好。我還想保留初始列,這樣我以后可以嘗試不同的組合。
非常感謝你。
uj5u.com熱心網友回復:
我們可以用
df1$new <- df1$latitude
df1$new[df1$latitude >=66] <- "66 "
或與ifelse
df1$new <- with(df1, ifelse(latitude >=66, "66 ", latitude))
-輸出
> df1
number latitude new
1 30 57 57
2 12 59 59
3 1 68 66
4 12 66 66
5 101 55 55
6 47 61 61
7 5 60 60
8 288 67 66
此外,正如@Mael 評論“新”列的型別,如果我們想保留型別,也可以使用pmin
library(dplyr)
df1 %>%
mutate(new = pmin(latitude, 66))
number latitude new
1 30 57 57
2 12 59 59
3 1 68 66
4 12 66 66
5 101 55 55
6 47 61 61
7 5 60 60
8 288 67 66
uj5u.com熱心網友回復:
選項mutate和ifelse:
library(dplyr)
df %>%
mutate(new = ifelse(latitude >= 66, "66 ", latitude))
輸出:
number latitude new
1 30 57 57
2 12 59 59
3 01 68 66
4 12 66 66
5 101 55 55
6 47 61 61
7 05 60 60
8 288 67 66
資料
df <- data.frame(number = c("30","12","01","12","101","47","05","288"),
latitude = c(57,59,68,66,55,61,60,67))
uj5u.com熱心網友回復:
library(tidyverse)
tribble(~"number", ~"latitude",
30, 57,
12, 59,
01, 68,
12, 66,
101,55,
47, 61,
05, 60,
288,67) %>%
dplyr::mutate(
new = if_else(latitude > 66,
"66 ",
as.character(latitude)))
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/458759.html
