CroatiaHR
CroatiaHR

Reputation: 625

Appending values as row in R

I have problems to add values to a data frame.
I have three variables that I want them in the end as one row.

a <- "aaa"
b <- "bbb"  
c <- [1,2,3,4,5,6,7]  

Now I want to append them as one row, where I would have three columns (each for one of the three variables a,b,c).

df <- data.frame()
colnames(df, c("a","b","c"))
df <- ("aaa", "bbb", [1,2,3,4,5,6,7])

Is this possible to do it?

Upvotes: 1

Views: 76

Answers (3)

ekstroem
ekstroem

Reputation: 6151

A data frame consists of vectors of the same length so you cannot get directly what you are asking with a data.frame since the c object is itself a vector. There are two possibilities: to recycle the shorter vectors or use a list:

Recycling:

A <- "aaa"
B <- "bbb"  
C <- c(1,2,3,4,5,6,7)
DF1 <- data.frame(A, B, C)

Then DF1 contains

    a   b c
1 aaa bbb 1
2 aaa bbb 2
3 aaa bbb 3
4 aaa bbb 4
5 aaa bbb 5
6 aaa bbb 6
7 aaa bbb 7

Using a list

L <- list(A, B, C)

Now L contains

[[1]]
[1] "aaa"

[[2]]
[1] "bbb"

[[3]]
[1] 1 2 3 4 5 6 7

and you could iterate over the list using, say, lapply() instead of considering it as a row.

Upvotes: 2

akrun
akrun

Reputation: 886938

With data.frame, we can wrap with list and use I (as is) to create a list column

data.frame(A, B, C = I(list(C)))
#    A   B            C
#1 aaa bbb 1, 2, 3,....

data

A <- "aaa"
B <- "bbb"  
C <- c(1,2,3,4,5,6,7)

Upvotes: 3

Edo
Edo

Reputation: 7818

I believe you shouldn't do it, but you can do it.

You need dplyr version >= 1.0.0 [you can do it even without, but it's cleaner this way]

library(dplyr)

# your input
a <- "aaa"
b <- "bbb"  
c <- c(1,2,3,4,5,6,7)

# I assumed your data should be looking like this:
df <- tibble(a = c("zzz", "yyy"),
             b = c("qqq", "www"),
             c = list(c(3,4,5,6,7,8,9),
                      c(2,3,4,5,6,7,8)))

# and this is the new row you want to add
newrow <- tibble(a = a, b = b, c = list(c))

# this is your result
bind_rows(df, newrow)

# # A tibble: 3 x 3
#   a     b     c        
#   <chr> <chr> <list>   
# 1 zzz   qqq   <dbl [7]>
# 2 yyy   www   <dbl [7]>
# 3 aaa   bbb   <dbl [7]>

A tibble is a better dataframe.

Note that the last column must be a list, because you want to host a vector of length > 1 in each row for that column.

Upvotes: 1

Related Questions