user8840683
user8840683

Reputation:

Transform a named vector to a data.frame R

I was wondering how I could achieve my desired output below in BASE R?

input <- c(a_1 = 2, a_2 = 3, b_1 = 1, b_2 = 0)

output <- data.frame(a = 2:3, b = 1:0)

Upvotes: 2

Views: 48

Answers (2)

thelatemail
thelatemail

Reputation: 93813

reshape can also take care of this automagically if you make your vector a data.frame. It will also separate the _x part out to a time variable in the output, so long as the variable names are always in the name_x pattern.

reshape(data.frame(t(input)), varying=TRUE, sep="_", direction="long")
#    time a b id
#1.1    1 2 1  1
#1.2    2 3 0  1

Upvotes: 1

akrun
akrun

Reputation: 887118

We can split based on the substring of the names of 'input' and convert to data.frame

data.frame(split(unname(input), sub("_\\d+$", "", names(input))))
#  a b
#1 2 1
#2 3 0

Or using unstack

nm1 <- sub('_\\d+$', '', names(input))
unstack(input ~ nm1, data.frame(input, nm1))

Or another option is matrix construction if the 'a', 'b' have equal lengths

matrix(input, ncol = 2,  dimnames = list(NULL, 
        unique(substring(names(input), 1, 1))))

Upvotes: 4

Related Questions