Quantcast
Channel: Active questions tagged r - Stack Overflow
Viewing all articles
Browse latest Browse all 201894

Using an if statement in apply in R for every value in a data frame

$
0
0

I have a data frame that I created using the read_excel function and then duplicated it. I'm going to explain it as if I was using Excel, because it's so easy to do this in Excel. I want to check if each cell in each row within columns 3 to 11 have a zero, and if so, put a zero in columns 12 to 20. If not, keep the original value.

Data2 <- Data1

Data2[,12:20] <- apply(Data1[,3:11],1:2,function(x) {if(x==0) {0})

This is the error message I get:

Warning message: In [<-.data.frame(*tmp*, , 12:20, value = list(0, 0, 0, 0, 0, : provided 450 variables to replace 9 variables

Example:

Data1 <- matrix(data=c(0,1,1,0,3,4,5,6,2,3,0,5,6,5,6,2,6,2,3,4,5,6,5,6),nrow=6,ncol=4)
Data2 <- Data1
Data2[,3:4] <- apply(Data1[,1:2],1:2,function(x) {if(x==0) {0})

Now gives error message:

Error: unexpected ')' in "Data2[,3:4] <- apply(Data1[,1:2],1:2,function(x) {if(x==0) {0})"


Viewing all articles
Browse latest Browse all 201894

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>