如何解决“替换$$-。data.frame中的错误有x行,数据有y”?

时间:2019-09-12 10:42:06

标签: r

我的目标是创建一个for循环,以将数据集的某些特定列转换为因子或整数。

条件将基于列的名称。


# Here is a small reproducible dataset
df <- data.frame(x = c(10,20,30), y = c("yes", "no", "no"), z = c("Big", "Small", "Average"))

# here is a vector that we are going to use inside our if statement
column_factor_names <- c("y", "z")

# for each column in df
for (i in names(df)) {

    print(i)

    # if it's a factor, convert into factor, else convert it into integer

    if (i %in% column_factor_names) {
        print("it's a factor")
        df$i <- as.factor(df$i)
    } else {
        print("it's an integer")
        df$i <- as.integer(df$i)
    }
}

运行此命令,我得到:Error in `$<-.data.frame`(`*tmp*`, "i", value = integer(0)) : replacement has 0 rows, data has 3

问题在于if-else语句中的行df$i <- as.factor(df$i)df$i <- as.integer(df$i)

但是我不理解的是,当我手动运行它时。 例如:

df$"x" <- as.integer(df$"x")
df$"y" <- as.factor(df$"y")
df$"z" <- as.factor(df$"z")

str(df)

正在工作:

'data.frame':   3 obs. of  3 variables:
 $ x: int  10 20 30
 $ y: Factor w/ 2 levels "no","yes": 2 1 1
 $ z: Factor w/ 3 levels "Average","Big",..: 2 3 1

我的问题是:为什么在for循环和if语句中不起作用?

2 个答案:

答案 0 :(得分:2)

在您的代码中,子集函数$查找名为i的列,而不是求值i。您可以选择使用[, i][[i]]来不同地子集data.frame:

x <- data.frame(x = c(10,20,30), y = c("yes", "no", "no"), z = c("Big", "Small", "Average"))

# here is a vector that we are going to use inside our if statement
column_factor_names <- c("y", "z")

# for each column in df
for (i in names(df)) {

  print(i)

  # if it's a factor, convert into factor, else convert it into integer

  if (i %in% column_factor_names) {
    print("it's a factor")
    x[[i]] <- as.factor(x[[i]])
  } else {
    print("it's an integer")
    x[[i]] <- as.integer(x[[i]])
  }
}

有关更多信息,请参见help("$")

如果您不介意丢失状态消息,则也可以无需循环就可以做到:

x[, i] <- as.factor(x[, i])

答案 1 :(得分:1)

针对您的循环部分更正的代码是:

# Here is a small reproducible dataset
df <- data.frame(x = c(10,20,30), y = c("yes", "no", "no"), z = c("Big", "Small", "Average"))

# here is a vector that we are going to use inside our if statement
column_factor_names <- c("y", "z")

for (i in names(df)) {
    print(i)
    if (i %in% column_factor_names) {
        print("it's a factor")
        df[,i] <- as.factor(df[,i])
    } else {
        print("it's an integer")
        df[,i] <- as.numeric(df[,i])
    }
 }