Gughan
Gughan

Reputation: 133

Return value by column name in R

I have a data set in the following format

ID 01 02 03 04 05 ID2 
1   1 NA NA NA NA 01
2   NA 2 NA 3  NA 04
3   NA NA 3 NA 1  05

Now i want to return the value in each row by ID2

for example in row 1 i want to return value 1 ,row 2 value 3 and so on based on the entries in the column ID2

ID Value
1   1
2   3
3   1

Thanks in advance

Upvotes: 1

Views: 618

Answers (2)

talat
talat

Reputation: 70336

You can use:

cbind(df[, "ID", drop = FALSE], Value = df[cbind(1:nrow(df), df$ID2+1)])
#  ID Value
#1  1     1
#2  2     3
#3  3     1

  • df[, "ID", drop = FALSE] selects the first column ("ID") and keeps it as a data.frame
  • df[cbind(1:nrow(df), df$ID2+1)] uses subsetting to get the rows 1:3 and columns according to column "ID2" +1 because the first column is not counted
  • cbinding the results returns a new data.frame.

Edit after comment:

If you have a modified example data set like the following, where column ID2 is factor and column 03 is missing:

df <- read.table(header=T, check.names = F, text = "
ID 01 02 03 04 05 ID2 
 1   1 NA NA NA NA 01
 2   NA 2 NA 3  NA 04
 3   NA NA 3 NA 1  05", colClasses = c(rep("integer", 6), "factor")) # read data

df$`03`<- NULL  # remove column 03

In this case you could modify the solution using match:

cbind(df[, "ID", drop = FALSE], Value = df[cbind(1:nrow(df), match(df$ID2, names(df)))])
#  ID Value
#1  1     1
#2  2     3
#3  3     1

Upvotes: 2

vck
vck

Reputation: 837

Try;

data.frame(ID=df$ID,Value=(sapply(1:nrow(df), function(x) df[x,df$ID2[x]+1])))

  ID Value
1  1     1
2  2     3
3  3     1

data:

df<-read.table(text="ID 01 02 03 04 05 ID2 
                     1   1 NA NA NA NA 01
                     2   NA 2 NA 3  NA 04
                     3   NA NA 3 NA 1  05",head=T)

Upvotes: 0

Related Questions