我想根据同一数据帧的列 CountryID 的内容向数据帧 df 添加列。我让它工作了,但我有 60 行复制粘贴行。
df$Country1 <- ifelse(as.integer(df$CountryID == 1), 1, 0)
df$Country2 <- ifelse(as.integer(df$CountryID == 2), 1, 0)
df$Country3 <- ifelse(as.integer(df$CountryID == 3), 1, 0)
... 60 more lines
为了使代码更有条理,我想编写一个函数 createColumns,我只需调用它即可执行括号内的整个代码。我最近的尝试没有创建任何列。 有谁知道如何解决这个问题吗?
createColumns <- function() {
df$Country1 <- ifelse(as.integer(df$CountryID == 1), 1, 0)
df$Country2 <- ifelse(as.integer(df$CountryID == 2), 1, 0)
df$Country3 <- ifelse(as.integer(df$CountryID == 3), 1, 0)
... 60 more lines
return(invisible())
}
最佳答案
您需要返回新对象:
createColumns <- function(df) {
df$Country1 <- ifelse(as.integer(df$CountryID == 1), 1, 0)
df$Country2 <- ifelse(as.integer(df$CountryID == 2), 1, 0)
df$Country3 <- ifelse(as.integer(df$CountryID == 3), 1, 0)
... 60 more lines
df
}
并这样使用它:
df <- createColumns(df)
您无法(轻松)修改 R 中的非本地对象,这是故意的:您不应该这样做。相反,应明确分配,如上所述。
还有一些其他事项需要注意;例如,重复您所写的内容 60 次应该是一个巨大的危险信号。重新思考问题:您可能一开始就不需要 60 列(相反,研究并使用 tidy data 的概念),但如果您真的这样做,您可能可以使用透视函数来替换这 60 行代码只需一行代码即可。
此外,R 还有逻辑数据类型。这意味着,在几乎所有用例中,您都会分配 TRUE
和 FALSE
而不是 1 和 0。因此,不要编写
ifelse(as.integer(df$CountryID == 1), 1, 0)
你可以将其简化为
df$CountryID == 1
此外,as.integer
调用完全是多余的:ifelse
需要一个逻辑参数,因此您当前的代码采用一个逻辑向量,将其显式转换为整数,然后通过 ifelse
将结果返回转换为逻辑向量。
关于r - 编写创建列的 R 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66636497/