[英]Populate a new column in a data frame with a vector of other columns in that row? R
So I have a data frame with columns "A", "B", "C", "D".所以我有一个包含“A”、“B”、“C”、“D”列的数据框。
I want a column df$Vector which would have c(A,B,C,D).我想要一个包含 c(A,B,C,D) 的 df$Vector 列。
For example if the data was like例如,如果数据是这样的
Name A B C D
1 0.5 0.7 0.6 0.9
2. 0.4 0.8 0.3 0.1
3 0.5 0.9. 0.1 0.2
Then the df$Vector will be like然后 df$Vector 就像
Name Vector
1 c(0.5,0.7,0.6,0.9)
2 c(0.4,0.8,0.3,0.1)
3 c(0.5,0.9,0.1,0.2)
What I've tried with df$Vector <- list(c(df$A...df$D) has made the list contain all the values rather than ones pertaining to that row. Anyone have any ideas?我用 df$Vector <- list(c(df$A...df$D) 尝试过的使列表包含所有值而不是与该行有关的值。有人有任何想法吗?
With transpose()
from data.table
:使用来自
data.table
的transpose()
:
df$vector = as.list(data.table::transpose(df[-1]))
df[2:5] <- NULL
name vector
1 1 1.0, 0.5, 0.7, 0.6, 0.9
2 2 2.0, 0.4, 0.8, 0.3, 0.1
3 3 3.0, 0.5, 0.9, 0.1, 0.2
Reproducible data:可重现的数据:
df = data.frame(
name = 1:3,
A = c(0.5, 0.4, 0.5), B = c(0.7, 0.8, 0.9),
C = c(0.6, 0.3, 0.1), D = c(0.9, 0.1, 0.2)
)
Could do like this:可以这样做:
library(tidyr)
library(dplyr)
library(purrr)
nest(df, -Name) %>%
mutate(
data = map(data, unlist, use.names = F)
) %>%
rename(Vector = data)
You could do:你可以这样做:
df$Vector <- lapply(seq(nrow(df)), function(x) c(df[x,]))
df <- df[c(1, 6)]
Which gives you这给你
df
#> Name Vector
#> 1 1 1.0, 0.5, 0.7, 0.6, 0.9
#> 2 2 2.0, 0.4, 0.8, 0.3, 0.1
#> 3 3 3.0, 0.5, 0.9, 0.1, 0.2
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.