Reputation: 167
I have DF which looks like
DF
Nrow a b c d
1 0.1 0.2 0.3 0.4
2 2 3 4 5
3 7 8 9 10
I want to subtract row 1 from row 2 and row 3.
How can i do it ? Thank you for any tips.
Updates
I saw this code: within-group differences from group member, and tried it as well.
Edited my data:
newdf <- df[!is.na(S[,1]),]
## df had NA values which was interfering with analysis, so I removed them.
df <- data.frame(treatment = rep(c('','baseline', 'treatment 1', 'treatment 2'), times=372),S[c(1:258)])
A <- df %>%
mutate_each(funs(. - .[treatment=="baseline"]), -treatment) %>%
filter(treatment!="baseline")
##have multiple columns for which I would like to calculate row-wise change
View(A)
However, now I thought to get correct results (or absolute change, i.e. row 2 - row 1), but the values are different from what I can calculate manually. Any thoughts?
Thanks!
Answers 11.03.2016
2-y Axes Plot with calculated absolute & relative Change in R
Upvotes: 1
Views: 30836
Reputation: 167
Answer 11.03.2016 #thought it might help others
This is how I finally did it:
library(dplyr)
dft1= filter(df, df$time==1)
dft2= filter(df, df$time==2)
dft3= filter(df, df$time==3)
You might need to rename data frame or columns in accordance to your data set.
To calculate absolute change from second to first time point & third to first time point:
abs1=dft2[33:290] - dft1[33:290]
abs2=dft3[33:290] - dft1[33:290]
To calculate relative change from second to first time point & third to first time point:
rel1=abs1/dft1[33:290]*100
rel2=abs2/dft1[33:290]*100
Upvotes: 0
Reputation: 3843
The following commands would perform the subtraction of 1st row from all the rows below, and will print the result of subtraction of 1st row from rows below.
data = data.frame(x=c(1,5,7,10),y=c(3,2,4,1.1),z=1:4)
data
# x y z
# 1 1 3.0 1
# 2 5 2.0 2
# 3 7 4.0 3
# 4 10 1.1 4
for(i in 2:nrow(data)){
result = data[i,] - data[1,]
print (result)
}
# x y z
# 2 4 -1 1 <--- 2nd row minus 1st row
# x y z
# 3 6 1 2 <--- 3rd row minus 1st row
# x y z
# 4 9 -1.9 3 <--- 4th row minus 1st row
Hope this helped. You can use the same commands for any number of rows in your data.
Upvotes: 0
Reputation: 6669
Use indexes to look at rows...
df <- read.table(textConnection("Nrow a b c d
1 0.1 0.2 0.3 0.4
2 2 3 4 5
3 7 8 9 10"), stringsAsFactors=FALSE, header=TRUE)
df[1, ] - df[2, ]
# or assign the result to a new row...
df <- rbind(df, df[1, ] - df[2, ])
Upvotes: 0
Reputation: 887961
If we need to subtract a single row from multiple rows, we can rep
the the single row to make the dimension as that of the subset of dataset with multiple rows and then do the subtraction.
DF[2:3, -1]- DF[rep(1,2),-1]
# a b c d
#2 1.9 2.8 3.7 4.6
#3 6.9 7.8 8.7 9.6
DF <- structure(list(Nrow = 1:3, a = c(0.1, 2, 7), b = c(0.2, 3, 8),
c = c(0.3, 4, 9), d = c(0.4, 5, 10)), .Names = c("Nrow",
"a", "b", "c", "d"), class = "data.frame",
row.names = c(NA, -3L))
Upvotes: 2