数据框的$和[]函数之间的区别

时间:2019-02-13 06:44:42

标签: r dataframe

如何和为什么,赋值时数据框的$和[]函数不同。 我可以调整abc.df[,"b"] = get("b")行使其具有与abc.df$b = get("b")相同的效果

abc.df = NULL
a = 1:10
abc.df = data.frame(a)
b_vector = 11:20
b_list = rep(list(c(1,2)),10)

sp_colmns1 = c("b_vector")
# This works :
abc.df$b_vector_method1 = get(sp_colmns1) # Method 1
abc.df[,"b_vector_method2"] = get(sp_colmns1) # Method 2
print(abc.df)

sp_colmns2 = c("b_list")
# Similarly : 
# The same code as above, but does not work
# Only difference is b_list is a list
abc.df$b_list_method1 = get(sp_colmns2) # Method 1 (Works)
# TODO: Need to get the reason for & Solve the error on following line
# abc.df[,"b_list_method2"] = get(sp_colmns2) # Method 2 (Doesnt work)
print(abc.df)

2 个答案:

答案 0 :(得分:0)

您可以添加任何名称"new"的列表,并在第二步中使用保存在其他位置的字符串来更改列名称。

abc.df$new <- get(sp_colmns2)
names(abc.df)[which(names(abc.df) == "new")] <- "b_list_method2"

# > head(abc.df)
#   a b_list_method2
# 1 1           1, 2
# 2 2           1, 2
# 3 3           1, 2
# 4 4           1, 2
# 5 5           1, 2
# 6 6           1, 2

答案 1 :(得分:0)

经过大量的反复试验,这似乎可行。 结果证明这是一个非常简单的解决方案...

list(get(sp_colmns2))而不是get(sp_colmns2)

abc.df = NULL
a = 1:10
abc.df = data.frame(a)
b_vector = 11:20
b_list = rep(list(c(1,2)),10)

sp_colmns1 = c("b_vector")
# This works :
abc.df$b_vector_method1 = get(sp_colmns1) # Method 1
abc.df[,"b_vector_method2"] = get(sp_colmns1) # Method 2
print(abc.df)

sp_colmns2 = c("b_list")
# Similarly : 
# The same code as above, but does not work
# Only difference is b_list is a list
abc.df$b_list_method1 = get(sp_colmns2) # Method 1 (Works)
# TODO: Need to get the reason for & Solve the error on following line
abc.df[,"b_list_method2"] = list(get(sp_colmns2)) # Method 2 (Doesnt work)
print(abc.df)