R 根据另一列中的观察值创建新列
我想根据R中的其他列在R中创建一个新列。格式是R 根据另一列中的观察值创建新列,r,R,我想根据R中的其他列在R中创建一个新列。格式是 new_column 0 1 0 0 1 我有三个变量,新列将从中生成 comorbidity date_of_comorbidity DOB 我尝试过使用ifelse,但出现了一个错误(这就是我尝试过的) newdata$newcolumn=DOB,newdata$newcolumnnewdata$newcolumn=newdata$DOB,1, ifelse(newdata$comorbity1==10&newdata$date\u of\
new_column 0 1 0 0 1
我有三个变量,新列将从中生成
comorbidity
date_of_comorbidity
DOB
我尝试过使用ifelse,但出现了一个错误(这就是我尝试过的)
newdata$newcolumn=DOB,newdata$newcolumnnewdata$newcolumn=newdata$DOB,1,
ifelse(newdata$comorbity1==10&newdata$date\u of\u comorbidity如果您可以扩展创建new\u列时要使用的标准,这将非常有用。
提供了一些关于如何获得最佳答案的好技巧
dplyr::mutate
是在数据帧中创建新列的简单方法。case\u when
有助于定义条件
创建数据:
library(tidyverse)
test_data <- test_data <- structure(list(comorbidity = c(0L, 0L, 1L, 1L, 1L, 1L, 1L, 1L,
0L, 1L), date_of_comorbidity = c(93L, 72L, 81L, 52L, 26L, 30L,
80L, 45L, 97L, 96L), DOB = c(123L, 145L, 192L, 176L, 189L, 164L,
158L, 170L, 145L, 121L)), row.names = c(NA, -10L), class = c("tbl_df",
"tbl", "data.frame"))
# A tibble: 10 x 3
comorbidity date_of_comorbidity DOB
<int> <int> <int>
0 93 123
0 72 145
1 81 192
1 52 176
1 26 189
1 30 164
1 80 158
1 45 170
0 97 145
1 96 121
ifelse
函数与使用if
和else
运算符不同。ifelse
如果第一个参数的计算结果为TRUE
,则返回第二个参数,否则返回第三个参数。因此,第二个和第三个参数不应尝试赋值(这回答了你的问题吗?很高兴我能帮忙。别忘了接受并投票!
Error in ifelse(newdata$comorbidity1==10 &newdata$date_of_comorbidity<DOB, :
argument "no" is missing
newdata$newcolumn<- ifelse(newdata$comorbidity1==10 & newdata$date_of_comorbidity>=newdata$DOB, 1,
ifelse(newdata$comorbidity1==10 & newdata$date_of_comorbidity<newdata$DO,0,NA))
library(tidyverse)
test_data <- test_data <- structure(list(comorbidity = c(0L, 0L, 1L, 1L, 1L, 1L, 1L, 1L,
0L, 1L), date_of_comorbidity = c(93L, 72L, 81L, 52L, 26L, 30L,
80L, 45L, 97L, 96L), DOB = c(123L, 145L, 192L, 176L, 189L, 164L,
158L, 170L, 145L, 121L)), row.names = c(NA, -10L), class = c("tbl_df",
"tbl", "data.frame"))
# A tibble: 10 x 3
comorbidity date_of_comorbidity DOB
<int> <int> <int>
0 93 123
0 72 145
1 81 192
1 52 176
1 26 189
1 30 164
1 80 158
1 45 170
0 97 145
1 96 121
test_data <- test_data %>%
mutate(new_column = case_when(comorbidity == 1 & date_of_comorbidity > 50 ~ TRUE,
comorbidity == 0 | date_of_comorbidity <= 50 ~ FALSE))
# A tibble: 10 x 4
comorbidity date_of_comorbidity DOB new_column
<int> <int> <int> <lgl>
1 1 99 115 TRUE
2 1 89 147 TRUE
3 1 55 188 TRUE
4 0 63 155 FALSE
5 1 38 179 FALSE
6 1 1 166 FALSE
7 1 17 139 FALSE
8 1 9 127 FALSE
9 1 96 181 TRUE
10 1 61 127 TRUE