Quantcast
Channel: Active questions tagged r - Stack Overflow
Viewing all articles
Browse latest Browse all 201867

Subtract a column in a dataframe from many columns in R

$
0
0

I have a dataframe. I'd like to subtract the 2nd column from all other columns. I can do it in a loop, but I'd like to do it in one call. Here's my working loop code:

df <- data.frame(x = 100:101, y = 2:3,z=3:4,a = -1:0,b=4:5)

for( i in 3:length(df) ) {
    df[i] <- df[i] - df[2]
}

Viewing all articles
Browse latest Browse all 201867

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>