KLM117
KLM117

Reputation: 467

creating a "for loop" in a single line of code

I've just started working with R/Rstudio, and I have made a simple for loop which looks at a dataset "Galaxies", takes Black holes with a mass greater than 9, and then divides their distance in light-years ("Distance") by 1000. I've now been asked how to perform this task in 1 line of code and I'm wondering what the best day to this was?

This is what I have managed so far:

for(i in 1:nrow(galaxies)){
if(galaxies$BlackHoleMass[i] > 9){
    print(galaxies[i,"Distance"]/1000)
    }
 }

I have tried this

galaxies[galaxies$BlackHoleMass>=9,print(galaxies[Distance]/1000

but I get the error: "unexpected symbol in:"

(Apologies, this is my first question on Stack Overflow so if I have left out/formatted something wrong let me know!)

Upvotes: 0

Views: 612

Answers (1)

maarvd
maarvd

Reputation: 1284

If I understand correctly you want to use a subset/filter (only select black holes with a mass > 9) and then divide the distance of them by 1000. Assuming its not necessary to print the result you could use this.

library(dplyr)
galaxies %>% filter(BlackHoleMass > 9) %>% mutate(Distance = Distance/1000)

But maybe the use of pipe functions is cheating ;)

Upvotes: 1

Related Questions