-1

快速提问:有人可以告诉我如何在 dplyr 语法中执行以下操作吗?

p4[,1:5] <- lapply(p4[,1:5] , factor)

Col 1 - 5 是角色,我希望它们成为因素。但是,使用 dplyr 我没有完成工作。我的猜测是:

df <- df %>% select(1:5) %>% mutate(as_factor)

但是由于选择功能,这会删除所有其他列。此外, mutate_if 在这里并不是很有帮助,因为我还有其他字符是我不想更改的字符。

非常感谢。

4

1 回答 1

1

在多个列上应用函数的一种方法是dplyr::across()函数。

我没有看到示例数据集,因此创建了我自己的一个。

library(dplyr)
data <- data.frame(
  stringsAsFactors = FALSE,
              col1 = c("apple", "pear"),
              col2 = c("wood", "fire"),
              col3 = c("cup", "plate"),
              col4 = c("pen", "pencil"),
              col5 = c("money", "coins")
)

data %>% 
  mutate(across(.cols = 1:5, .fns = factor)) %>% 
  str()
#> 'data.frame':    2 obs. of  5 variables:
#>  $ col1: Factor w/ 2 levels "apple","pear": 1 2
#>  $ col2: Factor w/ 2 levels "fire","wood": 2 1
#>  $ col3: Factor w/ 2 levels "cup","plate": 1 2
#>  $ col4: Factor w/ 2 levels "pen","pencil": 1 2
#>  $ col5: Factor w/ 2 levels "coins","money": 2 1
于 2021-06-10T08:54:48.120 回答