重复向量以填充数据框中的列 [英] Repeat vector to fill down column in data frame
问题描述
似乎这种非常简单的操作曾经为我工作,但现在却没有。问题的虚拟版本:
Seems like this very simple maneuver used to work for me, and now it simply doesn't. A dummy version of the problem:
df <- data.frame(x = 1:5) # create simple dataframe
df
x
1 1
2 2
3 3
4 4
5 5
df$y <- c(1:5) # adding a new column with a vector of the exact same length. Works out like it should
df
x y
1 1 1
2 2 2
3 3 3
4 4 4
5 5 5
df$z <- c(1:4) # trying to add a new colum, this time with a vector with less elements than there are rows in the dataframe.
Error in `$<-.data.frame`(`*tmp*`, "z", value = 1:4) :
replacement has 4 rows, data has 5
我期望它能产生以下结果:
I was expecting this to work with the following result:
x y z
1 1 1 1
2 2 2 2
3 3 3 3
4 4 4 4
5 5 5 1
即较短的向量应立即开始自动重复。我敢肯定,这曾经对我有用(它在一个我已经运行了一百次的脚本中没有出现问题)。现在,我什至无法使上面的虚拟示例按我的意愿工作。我缺少什么?
I.e. the shorter vector should just start repeating itself automatically. I'm pretty certain this used to work for me (it's in a script that I've been running a hundred times before without problems). Now I can't even get the above dummy example to work like I want to. What am I missing?
推荐答案
如果可以将向量均匀回收到data.frame中,则不会得到错误或警告:
If the vector can be evenly recycled, into the data.frame, you do not get and error or a warning:
df <- data.frame(x = 1:10)
df$z <- 1:5
这可能就是您以前遇到的。
This may be what you were experiencing before.
您可以使用 rep_len
使向量适应您的要求:
You can get your vector to fit as you mention with rep_len
:
df$y <- rep_len(1:3, length.out=10)
这将导致
df
x z y
1 1 1 1
2 2 2 2
3 3 3 3
4 4 4 1
5 5 5 2
6 6 1 3
7 7 2 1
8 8 3 2
9 9 4 3
10 10 5 1
请注意的 rep_len
中,可以使用更常见的 rep
函数:
Note that in place of rep_len
, you could use the more common rep
function:
df$y <- rep(1:3,len=10)
从帮助文件中获取 rep
:
rep.int
和rep_len
是两种常见情况下的简化版本。它们不是通用的。
rep.int
andrep_len
are faster simplified versions for two common cases. They are not generic.
这篇关于重复向量以填充数据框中的列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!