我有几十份调查数据档案.每一列都有几列数字数据,然后是几列字符数据.我需要根据两个都必须满足的标准,动态地从每个列中删除一列:
- 列是数字,并且...
- 该列包含单词"all".
我不能简单地取消 Select 包含单词"all"的任何/所有列,因为我必须保留的其中一个字符列的标题中有"all".
我不能简单地按名称或职位取消 Select 它,因为不同的文件在职位或名称方面不一致.它们唯一的共同点是,这一栏是数字and,标题中有"总体".此外,并不是所有的文件都有这样的列,这就是为什么我try 动态地这样做的原因.
下面是一个这样的文件的非常简化的示例,它显示在数据帧中:
#### reproducible example ####
columns <- c("rating A", "rating B", "Student Overall Rating",
"feedback 1", "feedback 2", "Student Overall Feedback")
c1 <- c(4, 4, 3)
c2 <- c(5, 4, 4)
c3 <- c(4.5, 4, 3.5)
c4 <- c("blah", "blah", "blah")
c5 <- c("blah", "blah", "blah")
c6 <- c("blahblah", "blahblah", "blahblah")
df <- as.data.frame(cbind(c1, c2, c3, c4, c5, c6))
names(df) <- columns
df$`rating A` <- as.numeric(df$`rating A`)
df$`rating B` <- as.numeric(df$`rating B`)
df$`Student Overall Rating` <- as.numeric(df$`Student Overall Rating`)
str(df) # shows relative structure I am dealing with
'data.frame': 3 obs. of 6 variables:
$ rating A : num 4 4 3
$ rating B : num 5 4 4
$ Student Overall Rating : num 4.5 4 3.5
$ feedback 1 : chr "blah" "blah" "blah"
$ feedback 2 : chr "blah" "blah" "blah"
$ Student Overall Feedback: chr "blahblah" "blahblah" "blahblah"
我进行了广泛的搜索,并try 了以下几种方法:
df <- df %>% select(!intersect(is.numeric(df), df %like% "Overall"))
这给了我:
Error in `select()`:
! Can't subset columns with `intersect(is.numeric(df), df %like% "Overall")`.
✖ `intersect(is.numeric(df), df %like% "Overall")` must be numeric or character, not `FALSE`.
我也试过...
df <- df %>% select(!where(is.numeric | contains("Overall")))
这将导致:
Error in `select()`:
! Problem while evaluating `where(is.numeric | contains("Overall"))`.
Caused by error in `is.numeric | contains("Overall")`:
! operations are possible only for numeric, logical or complex types
我希望得到的结果是,对于具有数字"学生总体评分"字段的文件:
'data.frame': 3 obs. of 5 variables:
$ rating A : num 4 4 3
$ rating B : num 5 4 4
$ feedback 1 : chr "blah" "blah" "blah"
$ feedback 2 : chr "blah" "blah" "blah"
$ Student Overall Feedback: chr "blahblah" "blahblah" "blahblah"
我知道我可以分别做select(where())
个条件,但有没有办法让它同时满足两个条件呢?有没有其他方法可以做到这一点?我真的在努力避免手动操作每个文件.