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?