在 R 中使用逻辑条件的 ifelse 语句
ifelse statement using logical condition in R
我有这个数据框
DF
ID WORD_LIST
1 APPLE
2 RED
3 SNOW
4 ANKARA
5 RENEW
我想 select 只有以“A”或“R”开头的单词
DF
ID WORD_LIST WORDS_A_R
1 APPLE APPLE
2 RED RED
3 SNOW NA
4 ANKARA ANKARA
5 RENEW RENEW
我试过这个代码
DF %>% mutate(WORDS_A_R = ifelse(grepl("^A" | "^R", WORD_LIST), as.character(WORD_LIST), NA))
但是出现这个错误
operations are possible only for numeric, logical or complex types
您可以使用:
transform(df, WORDS_A_R = ifelse(grepl("^[AR]", WORD_LIST), WORD_LIST, NA))
如果你喜欢 dplyr
:
library(dplyr)
df %>%
mutate(WORDS_A_R = ifelse(grepl("^[AR]", WORD_LIST), WORD_LIST, NA))
# ID WORD_LIST WORDS_A_R
#1 1 APPLE APPLE
#2 2 RED RED
#3 3 SNOW <NA>
#4 4 ANKARA ANKARA
#5 5 RENEW RENEW
您还可以将 base R
与 substring()
函数一起使用:
#Create condition
cond1 <- substr(DF$WORD_LIST,1,1)=='A' | substr(DF$WORD_LIST,1,1)=='R'
#Create var
DF$WORDS_A_R <- NA
DF$WORDS_A_R[cond1]<-DF$WORD_LIST[cond1]
ID WORD_LIST WORDS_A_R
1 1 APPLE APPLE
2 2 RED RED
3 3 SNOW <NA>
4 4 ANKARA ANKARA
5 5 RENEW RENEW
我有这个数据框
DF
ID WORD_LIST
1 APPLE
2 RED
3 SNOW
4 ANKARA
5 RENEW
我想 select 只有以“A”或“R”开头的单词
DF
ID WORD_LIST WORDS_A_R
1 APPLE APPLE
2 RED RED
3 SNOW NA
4 ANKARA ANKARA
5 RENEW RENEW
我试过这个代码
DF %>% mutate(WORDS_A_R = ifelse(grepl("^A" | "^R", WORD_LIST), as.character(WORD_LIST), NA))
但是出现这个错误
operations are possible only for numeric, logical or complex types
您可以使用:
transform(df, WORDS_A_R = ifelse(grepl("^[AR]", WORD_LIST), WORD_LIST, NA))
如果你喜欢 dplyr
:
library(dplyr)
df %>%
mutate(WORDS_A_R = ifelse(grepl("^[AR]", WORD_LIST), WORD_LIST, NA))
# ID WORD_LIST WORDS_A_R
#1 1 APPLE APPLE
#2 2 RED RED
#3 3 SNOW <NA>
#4 4 ANKARA ANKARA
#5 5 RENEW RENEW
您还可以将 base R
与 substring()
函数一起使用:
#Create condition
cond1 <- substr(DF$WORD_LIST,1,1)=='A' | substr(DF$WORD_LIST,1,1)=='R'
#Create var
DF$WORDS_A_R <- NA
DF$WORDS_A_R[cond1]<-DF$WORD_LIST[cond1]
ID WORD_LIST WORDS_A_R
1 1 APPLE APPLE
2 2 RED RED
3 3 SNOW <NA>
4 4 ANKARA ANKARA
5 5 RENEW RENEW