Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Indexing within a dataframe

The task is to multiply all negative numbers by 10 in ‘df’.

So I am only able to multiply everything by 10 but when I add an if-statement then everything stops working.

df =

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

x <- c('a', 'b', 'c', 'd', 'e')
y <- c(-4,-2,0,2,4)
z <- c(3, 4, -5, 6, -8)
# Join the variables to create a data frame

df <- data.frame(x,y,z)
df
##
  x  y  z
1 a -4  3
2 b -2  4
3 c  0 -5
4 d  2  6
5 e  4 -8

my code so far

df2 <- df
df2


for(i in 2:ncol(df2)) {       
  df2[ , i] <- df2[ , i] *10
}
df2

>Solution :

 cbind(df[1], 10^(df[-1] < 0) * df[-1])

  x   y   z
1 a -40   3
2 b -20   4
3 c   0 -50
4 d   2   6
5 e   4 -80
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading