【问题标题】:How to recode multiple columns using for-loop in R如何在 R 中使用 for 循环重新编码多列
【发布时间】:2021-06-23 10:33:31
【问题描述】:

我在重新编码 R 中的多个列时遇到问题。 这是我到目前为止的代码:

library(car)
c1 <- sample(1:5, 100, TRUE)
c2 <- sample(1:5, 100, TRUE)
c3 <- sample(1:5, 100, TRUE)
data <- data.frame(c1,c2,c3)

col_names <- colnames(data[c(1,3)])
for (name in col_names) {
  data$name <- recode(data$name, "1=5; 2=4; 3=3; 4=2;5=1")
}

在 for 循环之前一切正常。错误说

Error: Assigned data `recode(df_meme$name, "1=5; 2=4; 3=3; 4=2;5=1")` must be compatible with existing data.
x Existing data has 203 rows.
x Assigned data has 0 rows.
i Only vectors of size 1 are recycled.
Run `rlang::last_error()` to see where the error occurred.
Zusätzlich: Warnmeldung:
Unknown or uninitialised column: `name`. 

非常感谢您的回答!谢谢。

【问题讨论】:

  • 尝试在for-loop 中使用data[[name]] 而不是data$name
  • 谢谢!那行得通。

标签: r for-loop recode


【解决方案1】:

您可以在dplyr 中使用across -

library(dplyr)

data <- data %>% mutate(across(all_of(col_names), 
                  car::recode, "1=5; 2=4; 3=3; 4=2;5=1"))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-02-17
    • 1970-01-01
    • 1970-01-01
    • 2017-01-09
    • 1970-01-01
    • 1970-01-01
    • 2023-03-20
    相关资源
    最近更新 更多