0

I'm trying to convert a series of repetitive code into a user-defined function. The code references the row location by row number and the column by name (in double quotes). The code works as presented, but with many columns to repeat (this is just an example), it is inefficient.

data1<-data.frame(A=1:4,B=c(8,11,10,9999),C=c(9999,8,4,10),D=c(21:24))
namescol<-c("valueA","valueB","valueC","valueD")
colnames(data1)<-namescol

if(data1[1,"valueB"]!=9999){
data1[2,"valueA"]<-data1[1,"valueB"]
}
if(data1[1,"valueC"]!=9999){
data1[3,"valueA"]<-data1[1,"valueC"]
}
if(data1[1,"valueD"]!=9999){
data1[4,"valueA"]<-data1[1,"valueD"]
}

I converted the block of if statements into a single function, replacing the name of the column and the row number in the function.

testfcn<-function(column,x){
if(data1[1,column]!=9999){
data1[x,"valueA"]<-data1[1,column]
}

testfcn("valueB",2)
testfcn("valueC",3)
testfcn("valueD",4)
}

This function produces no error, but does not substitute the values in the first row of the columns into subsequent rows of the first column. According to this post, Pass a data.frame column name to a function, passing column names should work. Any ideas?

MeggSho
  • 11
  • 2

1 Answers1

0

R functions don't directly modify objects like data frames inside a function. Functions work with a copy of your object with the same original values. You are changing the value of data1, but only within the scope of your function. Try returning data1 at the end of your function, and assigning the result of the function call back to the data1 object:

testfcn<-function(column,x) {
  if(data1[1,column]!=9999){
    data1[x,"valueA"]<-data1[1,column]
  }
  data1 # this returns the modified data1
}

data1 <- testfcn("valueD",4)
cmaimone
  • 546
  • 4
  • 8