Reputation: 35
i have a dataframe with many columns and rows, i need to for each column subtract the first row from other rows.
C1 C2 C3
3 7 9
4 9 4
7 6 11
9 4 8
Upvotes: 1
Views: 5688
Reputation: 193687
You can actually subtract fairly directly, but you need to provide the first row as a list
:
mydf - as.list(mydf[1, ])
# C1 C2 C3
# 1 0 0 0
# 2 1 2 -5
# 3 4 -1 2
# 4 6 -3 -1
## OR
mydf - c(mydf[1, ])
Upvotes: 12
Reputation: 887951
We can replicate the first row to create the lengths same and then do the difference.
df1-df1[1,][col(df1)]
# C1 C2 C3
#1 0 0 0
#2 1 2 -5
#3 4 -1 2
#4 6 -3 -1
Or another option is transposing (t
) the dataset, get the difference and transpose it again, which may be less efficient
t(t(df1)- unlist(df1[1,]))
# C1 C2 C3
#[1,] 0 0 0
#[2,] 1 2 -5
#[3,] 4 -1 2
#[4,] 6 -3 -1
Upvotes: 2