Home > Net >  Populate a new column in a data frame with a vector of other columns in that row? R
Populate a new column in a data frame with a vector of other columns in that row? R

Time:03-12

So I have a data frame with columns "A", "B", "C", "D".

I want a column df$Vector which would have c(A,B,C,D).

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

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?

CodePudding user response:

With transpose() from data.table:

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

enter image description here

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)
)

CodePudding user response:

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

CodePudding user response:

Could do like this:

library(tidyr)
library(dplyr)
library(purrr)
nest(df, -Name) %>%
  mutate(
    data = map(data, unlist, use.names = F)
  ) %>%
  rename(Vector = data)
  • Related