0

Is there any way to do something like this in R without having 6 samples but just 2?

> df <- data.frame(w=c(1,2),x=c('asdf','yxcv'), y=c(1234, 5678), z=c(c(1,2,3,4), c(5,6,7,8)))
> df
  w    x    y z
1 1 asdf 1234 1
2 2 yxcv 5678 2
3 1 asdf 1234 3
4 2 yxcv 5678 4
5 1 asdf 1234 5
6 2 yxcv 5678 6
7 1 asdf 1234 7
8 2 yxcv 5678 8

I would like to and get and be able to use a vector when I do something like:

> df$z[1]
[1] 1 2 3 4
> sum(df$z[1])
[1] 10

Or get the following when selecting a row:

> df[1,]
  w    x    y  z
1 1 asdf 1234  c(1,2,3,4)

This post does something similar but does not resolve the problem of using the vectors as vectors.

SePeF
  • 725
  • 7
  • 13

1 Answers1

1

You can follow the answer in the link you provided. Just note that lapply returns an object of class "list". All you need to do is to create a dataframe without the final column z and assign a list to that column.

df <- data.frame(w=c(1,2),x=c('asdf','yxcv'), y=c(1234, 5678))
df$z <- list(c(1,2,3,4), c(5,6,7,8))

Now it works as requested.

df
#  w    x    y          z
#1 1 asdf 1234 1, 2, 3, 4
#2 2 yxcv 5678 5, 6, 7, 8

Extraction. Note the difference between [ and [[.

df$z[1]
#[[1]]
#[1] 1 2 3 4

df$z[[1]]
#[1] 1 2 3 4

And operations on the list members.

sum(df$z[1])
#Error in sum(df$z[1]) : 'type' inválido (list) do argumento

sum(df$z[[1]])
#[1] 10
Rui Barradas
  • 70,273
  • 8
  • 34
  • 66