如何在数据帧中添加命名向量,并根据数据帧的列名对向量的组成进行重新排序?
我需要一次建立一个数据框。命名向量通过一些处理获得,它提供要插入的行的值。问题在于命名向量没有与数据帧列相同顺序的成分。这将rbind导致产生错误的结果。这是非常简化的示例代码:
df = data.frame(id=1:2, va=11:12, vb=21:22, vc=31:32)
v1 = c(id=4, va=14, vb=25, vc=NA)
df = rbind(df, v1)
Run Code Online (Sandbox Code Playgroud)
到目前为止,效果如此之好。现在,下一个向量处理将导致:
v2 = c(va=19, id=9, vc=34, vb=NA)
df = rbind(df, v2)
Run Code Online (Sandbox Code Playgroud)
这会产生错误的结果。正确的结果应该是
id va vb vc
1 1 11 21 31
2 2 12 22 32
3 4 14 25 NA
4 9 19 NA 34
Run Code Online (Sandbox Code Playgroud) 我需要将 lm fit 对象存储在数据框中以进行进一步处理(这是必需的,因为我将在数据框中存储大约 200 多个回归)。我无法将 fit 对象存储在数据框中。以下代码产生错误消息:
x = runif(100)
y = 2*x+runif(100)
fit = lm(y ~x)
df = data.frame()
df = rbind(df, c(id="xx1", fitObj=fit))
Error in rbind(deparse.level, ...) :
invalid list argument: all variables should have the same length
Run Code Online (Sandbox Code Playgroud)
我想获取 dplyr 的“do”调用返回的数据框,示例如下:
> tacrSECOutput
Source: local data frame [24 x 5]
Groups: <by row>
sector control id1 fit count
1 Chemicals and Chemical Products S tSector <S3:lm> 2515
2 Construation and Real Estate S tSector <S3:lm> 985
Run Code Online (Sandbox Code Playgroud)
请注意,这只是一个示例输出。我想以上述格式创建数据框(适合 …