【问题标题】:Error in `$<-.data.frame`(`*tmp*`, marital1, value = numeric(0)) : replacement has 0 rows, data has 526`$<-.data.frame`(`*tmp*`, marital1, value = numeric(0)) 中的错误:替换有 0 行,数据有 526
【发布时间】:2020-09-06 20:19:29
【问题描述】:

有一个包含工资的 CSV 文件。

试图将定性变量转换为数值变量。变量是“marital”,其中 1 表示已婚,0 表示未婚。

wages = read.csv("Desktop/wages.csv")

wages$marital1=as.numeric(wages$marital1=="married")

继续

Error in `$<-.data.frame`(`*tmp*`, marital1, value = numeric(0)) :
replacement has 0 rows, data has 526

【问题讨论】:

    标签: r


    【解决方案1】:

    可能有点晚了,但如果您仍在寻找解决方案,您可以尝试在您的数据框上运行以下命令。注意,这个命令会在整个数据框wages上运行:

    wages = type.convert(wages, as.is = TRUE)
    

    要仅操作选择性列,即将它们转换为factor,您可以执行以下操作:

    # Column selection can be done by name or by the position of the column
    names = c('marital1') # Select as many or as few columns
    wages[,names] <- lapply(wages[,names] , factor)
    

    相应地,您可以将部分或全部变量转换为character,如下所示:

    names = c('marital1') # You can select as many or as few columns as you want
    wages[,names] <- sapply(wages[,names] , factor)
    

    希望对你有帮助!

    【讨论】:

      【解决方案2】:

      你需要检查你的变量名(列名),这个问题的原因通常是因为你的函数中的变量名和数据框中的变量名(列名)不同。

      【讨论】:

        【解决方案3】:

        尝试:

        wages$marital1 = (wages$marital1=="married") * 1
        

        【讨论】:

        • 还是同样的错误! > 工资$marital1 = (wages$marital1=="married") * 1 $&lt;-.data.frame(*tmp*, marital1, value = numeric(0)) 中的错误:替换有 0 行,数据有 526
        猜你喜欢
        • 1970-01-01
        • 2019-01-10
        • 2021-12-30
        • 2020-09-03
        • 1970-01-01
        • 2020-06-29
        • 2018-04-10
        • 2014-06-20
        • 2021-07-08
        相关资源
        最近更新 更多