calculation between columns in a dataframe or between dataframe

Hi,
Just came across a little problem when practicing R. If I want to columns in d(except the first) to substract the first column in d, I make it based the example code. Is there anything not serious and reasonable, and other ways? And if some calculations between dataframes, dataframes must be equal size?
Any help would be appreciated.

d <- data.frame(n1 = c(7.3,12.5,18.4,15.0,11.8,13.7,10.2,9.5,7.6,2.5),
                n2 = c(5.2,6.0,5.5,2.0,NA,6.7,5.6,3.5,10.4,6.8),
                n3 = c(5.6,5.8,13.3,13.8,3.0,10.1,10.7,7.7,12.3,15.8),
                n4 = c(6,3.3,2.6,3.8,19,23,24,25,29,2.9))
d1<-d[,-1]-d$n1

Created on 2023-06-03 with reprex v2.0.2

d <- data.frame(n1 = c(7.3,12.5,18.4,15.0,11.8,13.7,10.2,9.5,7.6,2.5),
                n2 = c(5.2,6.0,5.5,2.0,NA,6.7,5.6,3.5,10.4,6.8),
                n3 = c(5.6,5.8,13.3,13.8,3.0,10.1,10.7,7.7,12.3,15.8),
                n4 = c(6,3.3,2.6,3.8,19,23,24,25,29,2.9))

# subtract all rows of d[,1] from all rows of d[,2:4]

(d1 <- d[,2:4] - d[,1])
#>       n2   n3    n4
#> 1   -2.1 -1.7  -1.3
#> 2   -6.5 -6.7  -9.2
#> 3  -12.9 -5.1 -15.8
#> 4  -13.0 -1.2 -11.2
#> 5     NA -8.8   7.2
#> 6   -7.0 -3.6   9.3
#> 7   -4.6  0.5  13.8
#> 8   -6.0 -1.8  15.5
#> 9    2.8  4.7  21.4
#> 10   4.3 13.3   0.4

Created on 2023-06-02 with reprex v2.0.2

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.