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?
Asked
Active
Viewed 71 times
0
-
6See [How to make a great R reproducible example]( https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example/5963610#5963610) – TarJae Feb 22 '22 at 21:22
-
3so you didn't run the code yet? what have you tried – Mike Feb 22 '22 at 21:22
-
3Welcome to SO. Please don't present code as images if you can avoid it - potential answerers will want to copy and paste and run your code to test. And --^ the link from TarJae is useful too. Having data we can work with is very important, even if it's just included sample data like `mtcars` adapted to your problem. – thelatemail Feb 22 '22 at 21:24
-
2Are `mdrows.empty()` and `mdrows.length` R code, or is that Python? – Jon Spring Feb 22 '22 at 21:44
1 Answers
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

Allrounder
- 31
- 6
-
wait why is the if statement condition i==1? shouldn't the condition be dat[,i]=="h353" portion? – thecurryman23 Feb 23 '22 at 00:15
-
No, this for the loop, the first iteration (i==1) creates the mdrow object (a logical vector), which is subsequently combined with the results of the following iterations using OR. The final logical vector lets you swap the ones for the zeros at the right places. – Allrounder Feb 23 '22 at 06:45
-
ah ok I get it. It worked on the dataset you provided, but when I ran it on my dataset, mdrows only has a False in the first position and then the rest of it is null. Any idea why? also what does "|" mean? – thecurryman23 Feb 24 '22 at 17:36
-
As simple as my code is, it should also work for your data. Without looking at directly, I can't tell why it does not. The | is a logical OR, if you haven't seen it before, then maybe you want to consult an R tutorial, here's a good one: https://bookdown.org/rdpeng/rprogdatascience/ – Allrounder Feb 24 '22 at 17:55