在数据框 `$<-.data.frame` 中出现错误:将 0 行替换为 `marital1` 的值,但数据有 526 行。

3

有一份薪资的CSV文件。

试图将一个定性变量转换为数值变量。该变量是“婚姻状况”,其中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
3个回答

4

您需要检查变量名(列名),通常出现此问题的原因是函数中的变量名与数据框中的变量名(列名)不同。


0

可能有点晚了,但如果您仍在寻找解决方案,可以尝试在数据框上运行以下命令。请注意,此命令将在整个数据框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)

相应地,您可以将一些或所有变量转换为字符,如下所示:

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

希望对你有所帮助!


0

尝试:

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

仍然是同样的错误!> wages$marital1 = (wages$marital1=="married") * 1 在 $<-.data.frame(*tmp*, marital1, value = numeric(0)) 中出现错误: 替换行数为0,数据有526行。 - user13582101

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接