【问题标题】:Is there a way to add only a name to an r data.frame? [duplicate]有没有办法只向 r data.frame 添加一个名称? [复制]
【发布时间】:2021-01-07 14:59:40
【问题描述】:

有没有办法将新列添加到 data.frame 并用 NA 填充它们(由稍后的函数填充),其中新列的标题来自字符向量(字符串)。

示例:
我想做的是根据这个data.frame的主题列添加一些新列

exam_results <- data.frame(
  subject = c("maths", "economics", "chemistry"),
  final_score = c(70, 78, 61),
  midterm_score = c(53, 66,40)
)

即:

# new object for new df
exam_results_new_columns <- exam_results

# get the names of the different subjects
subjects <- unique(exam_results$subject)

column_names <- c()

for (i in 1:length(subjects)) {
  column_names[i] <- paste0("subject_", subjects[i])
  exam_results_new_columns$i <- NA
}

这将产生以下df:

subject final_score midterm_score i
maths 70 53 NA
economics 78 66 NA
chemistry 61 40 NA

但我想要的是:

subject final_score midterm_score subject_economics subject_chemistry
maths 70 53 NA NA
economics 78 66 NA NA
chemistry 61 40 NA NA

有什么方法可以实现吗?

【问题讨论】:

  • 试试exam_results_new_columns[[column_names[i]]] &lt;- NA

标签: r dataframe


【解决方案1】:

for循环中,使用方括号[]而不是美元符号$

subjects <- unique(exam_results$subject)
column_names <- paste0("subject_", subjects)

for(i in column_names)
  exam_results_new_columns[,i] <- NA

输出

#     subject final_score midterm_score subject_maths subject_economics subject_chemistry
# 1     maths          70            53            NA                NA                NA
# 2 economics          78            66            NA                NA                NA
# 3 chemistry          61            40            NA                NA                NA

【讨论】:

    猜你喜欢
    • 2019-10-05
    • 2014-04-18
    • 2018-11-21
    • 2020-03-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多