0

我有这个数据框

DF
ID    WORD_LIST   
1     APPLE
2     RED
3     SNOW
4     ANKARA
5     RENEW

我只想选择以“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
4

2 回答 2

2

您可以使用 :

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
于 2020-07-10T12:49:04.040 回答
1

您还可以使用base Rwithsubstring()函数:

#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
于 2020-07-10T13:00:21.883 回答