'I need a faster way of doing this instead of using for loops in R [closed]
So what I'm trying to do is add a column of 0's to this data frame, but if any of the rows has the code "h353" within any of the columns in that row, then I want that row to have a 1 instead of a 0 in the new column. I'm not even sure if the code works as is, but I just know it's going to take forever to run in its current state since the file is pretty large. Any suggestions on how to fix this/make it more efficient?
Solution 1:[1]
This should do the job:
dat<-data.frame(x=rep(0,30), y=rep(0,30), z=rep(0,30))
dat[2,2]<-"h353"
dat[15,3]<-"h353"
dat[20,1]<-"h353"
dat$md<-0
for (i in 1:length(dat[1,])) {if (i==1){mdrows<-as.character(dat[,i])=="h353"} else {mdrows<-mdrows|as.character(dat[,i])=="h353"}}
dat$md[mdrows]<-1
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Allrounder |
