【发布时间】:2021-03-15 10:46:39
【问题描述】:
我想根据同一数据框的 Column 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())
}
【问题讨论】: