shiva
shiva

Reputation: 21

How to look up values in R based on row and column

i have a data frame which is

name val1 val2 
A      2    3
B      5    6
C      7    9

i want a dataframe

name Grp value
A    val1  2
B    val1  5
C    val1  7
A    val2  3
B    val2  6
C    val2  9

what is the optimal solution ?

Upvotes: 2

Views: 131

Answers (4)

David Arenburg
David Arenburg

Reputation: 92300

Or just use melt from reshape2 package

library(reshape2)
melt(df)
#   name variable value
# 1    A     val1     2
# 2    B     val1     5
# 3    C     val1     7
# 4    A     val2     3
# 5    B     val2     6
# 6    C     val2     9

Edit: per @AnandaMahtos comment, if you insist on having your variable name called Grp, you can alternatively do:

melt(df, variable.name = "Grp")

Upvotes: 3

sandro scodelller
sandro scodelller

Reputation: 430

Or without any extra package:

ddff<- data.frame(name=c("A","B","C"),val1=c(2,5,7),val2=c(3,6,9))  
ddff2<- reshape(ddff,direction="long", varying = list(names(ddff)[2:3]),v.names=c("values"),times=c("val1","val2"))[,1:3]  

ddff2
#       name time values  
#1.val1    A val1      2  
#2.val1    B val1      5
#3.val1    C val1      7
#1.val2    A val2      3
#2.val2    B val2      6
#3.val2    C val2      9

Upvotes: 1

akrun
akrun

Reputation: 887951

A base R option would be to use stack

cbind(name=df$name, stack(df, select=-name))
#   name values  ind
#1    A      2 val1
#2    B      5 val1
#3    C      7 val1
#4    A      3 val2
#5    B      6 val2
#6    C      9 val2

Upvotes: 1

talat
talat

Reputation: 70336

It's called reshaping a data.frame from wide to long format. One option to do that would be, using the package tidyr:

library(tidyr)

gather(df, Grp, Value, -name)
#  name  Grp Value
#1    A val1     2
#2    B val1     5
#3    C val1     7
#4    A val2     3
#5    B val2     6
#6    C val2     9

Upvotes: 3

Related Questions