简体   繁体   English

使用该行中其他列的向量填充数据框中的新列? R

[英]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.tabletranspose()

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.

相关问题 R将数据框列合并为向量的新列 - R merge data frame columns to a new column as a vector 根据 R 中数据框中的其他列创建新列 - Creating new column based on other columns in data frame in R 将数据框中的多个列与向量进行比较,并将新列添加到数据框中,指示 R 中匹配的 cloumn 名称 - compare multiple columns in a data frame with vector and add new column to the data frame indicating the matched cloumn name in R 在数据框R中动态创建列,并根据其他列条件填充 - Create columns dynamically in data frame R and populate based on other column condition R 使用不同的数据框列条件填充新列 - R using different data frame column conditions to populate new column 通过将数据框中的列名称与行值匹配来填充列 - Populate columns by matching name of column in data-frame with row values 根据条件语句从其他列填充R中的新列 - Populate new column in R from other columns based on conditional statement 将数据框行转换为新的数据框列R - Convert data frame row into new data frame column R 根据 R 中数据框中所有其他列中的字符串值,使用 dplyr 创建一个新列 - Create a new column using dplyr based on string values in all other columns in a data frame in R 在 R data.frame 中添加一个新列转换所有其他列的类型 - Adding a new column in R data.frame converts the type of all other columns
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM