[英]Add vector as a column to a data.frame with fill = NA
I have a vector of length 3 ( my_vector
).我有一个长度为 3 的向量(
my_vector
)。
I want to bind this vector to an existing data.frame ( my_df
) as a new column.我想将此向量绑定到现有的 data.frame (
my_df
) 作为新列。
However, the data.frame has 4 rows.但是,data.frame 有 4 行。 Thus, in the 4th row, the new column value (or
my_df[4,3]
) should be NA
.因此,在第 4 行,新列值(或
my_df[4,3]
)应该是NA
。
How can I achieve this?我怎样才能做到这一点?
When I do my_df$new_column <- my_vector
, I get the following error message: replacement has 3 rows, data has 4当我执行
my_df$new_column <- my_vector
时,我收到以下错误消息: replacement has 3 rows, data has 4
Here is my_df
(comprising 4 rows):这是
my_df
(包括 4 行):
> dput(my_df)
structure(list(
person = c("Oleg", "Yurii", "Igor", "Mikhail"),
role = structure(c(1L, 2L, 2L, 3L), class = "factor", .Label = c("EDITOR-IN-CHIEF", "DEPUTY EDITORS-IN-CHIEF", "Coordinating Editor"))),
class = "data.frame", row.names = c(NA, -4L)
)
And my_vector
(of length 3):和
my_vector
(长度为 3):
> dput(my_vector)
c("Lomonosov University", "Russian Academy of Sciences", "Institute of Acoustics, Moscow, Russia")
We create a NA
column and then assign the 'my_vector' based on the length of the vector.我们创建一个
NA
列,然后根据向量的长度分配“my_vector”。 Here seq_along(my_vector)
return 1:3
, thus the first 3 elements are replaced with 'my_vector' values这里
seq_along(my_vector)
返回1:3
,因此前 3 个元素被替换为 'my_vector' 值
my_df$new_column <- NA_character_
my_df$new_column[seq_along(my_vector)] <- my_vector
Or this can be done in a single step if we pad NA
at the end by making use of length<-
或者,如果我们在最后使用
length<-
填充NA
,这可以一步完成
my_df$new_column <- `length<-`(my_vector, nrow(my_df))
-output -输出
my_df
# person role new_column
#1 Oleg EDITOR-IN-CHIEF Lomonosov University
#2 Yurii DEPUTY EDITORS-IN-CHIEF Russian Academy of Sciences
#3 Igor DEPUTY EDITORS-IN-CHIEF Institute of Acoustics, Moscow, Russia
#4 Mikhail Coordinating Editor <NA>
You could subset the values from my_vector
which has same length as my_df
.您可以子集
my_vector
中的值,其长度与my_df
相同。
my_df$new_column <- my_vector[seq_len(nrow(my_df))]
my_df
# person role new_column
#1 Oleg EDITOR-IN-CHIEF Lomonosov University
#2 Yurii DEPUTY EDITORS-IN-CHIEF Russian Academy of Sciences
#3 Igor DEPUTY EDITORS-IN-CHIEF Institute of Acoustics, Moscow, Russia
#4 Mikhail Coordinating Editor <NA>
A data.table
option data.table
选项
setDT(my_df)[, new := NA][, new := replace(new, seq_along(my_vector), my_vector)]
gives给
> my_df
person role new
1: Oleg EDITOR-IN-CHIEF Lomonosov University
2: Yurii DEPUTY EDITORS-IN-CHIEF Russian Academy of Sciences
3: Igor DEPUTY EDITORS-IN-CHIEF Institute of Acoustics, Moscow, Russia
4: Mikhail Coordinating Editor <NA>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.