有没有办法根据逻辑数据帧对数据帧进行子集划分,并在R中保留原始数据帧结构?
我一直在争论一些非结构化文本,我将短语分成了不同的字段,主要是为了可读性。生成的数据帧与此类似,即它包含NAs:有没有办法根据逻辑数据帧对数据帧进行子集划分,并在R中保留原始数据帧结构?,r,tidyverse,R,Tidyverse,我一直在争论一些非结构化文本,我将短语分成了不同的字段,主要是为了可读性。生成的数据帧与此类似,即它包含NAs: behaviour <- data.frame(field_1 = c("cat eats meal", "cat watches fish", "cat watches frog", NA), field_2 = c("bird flies away", "cat watches bird", "cat watches fish
behaviour <- data.frame(field_1 = c("cat eats meal", "cat watches fish", "cat watches frog", NA),
field_2 = c("bird flies away", "cat watches bird", "cat watches fish", NA),
field_3 = c("cat is bored", NA, NA, "cat watches sky"))
我希望获得一个新的数据帧,其中只有手表中的相应值为真时,行为中的值才会保留,并且原始数据帧的结构会保留。我尝试通过行为[watches]将两者转换为矩阵和子集,但输出是一个没有保留结构的字符向量
我现在想知道这是否涉及一种变异的行为,即如果watchs==T,那么在行为中粘贴或保留原始值
提前谢谢 由于您已经有手表,您可以直接分配NA:
在base R中,我们可以使用lappy和grepl
watches <- behaviour %>%
map_df(~ str_detect(., "watches"))
behaviour
watches
behaviour[!watches] <- NA
library(dplyr)
behaviour %>% mutate_all(~replace(., !stringr::str_detect(., "watches"), NA))
# field_1 field_2 field_3
#1 <NA> <NA> <NA>
#2 cat watches fish cat watches bird <NA>
#3 cat watches frog cat watches fish <NA>
#4 <NA> <NA> cat watches sky
behaviour[] <- lapply(behaviour, function(x) replace(x, !grepl('watches', x), NA))
#or with grep
#behaviour[] <- lapply(behaviour, function(x) replace(x, -grep('watches', x), NA))