用于遍历dataframe和data.table列名称

问题描述

我有两个几乎相同的对象,其中一个是数据框,另一个是data.table。我想遍历两个列,并在数据框的列上运行索引。这是我的代码

library(data.table)

df_1 <- data.frame(col_1 = c(1,2),col_2 = c(3,4))
df_2 <- as.data.table((df_1))

for (el in colnames(df_1)){
  print(df_1[el])
  print(df_2[el])
}

它失败并显示错误

Error in `[.data.table`(df_2,el) : 
  When i is a data.table (or character vector),the columns to join by must be specified using 'on=' argument (see ?data.table),by keying x (i.e. sorted,and,marked as sorted,see ?setkey),or by sharing column names between x and i (i.e.,a natural join). Keyed joins might have further speed benefits on very large data due to x being sorted in RAM.

我也尝试过:

for (el in seq_along(colnames(df_1))){
  print(el)
  print(df_1[el])
  print(df_2[,el])
}

这是错误消息:

Error in `[.data.table`(df_2,el) : 
  j (the 2nd argument inside [...]) is a single symbol but column name 'el' is not found. Perhaps you intended DT[,..el]. This difference to data.frame is deliberate and explained in FAQ 1.1.

有什么想法吗?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)