[英]R identifying first value in data-frame and creating new variable by adding/subtracting this from all values in data-frame in new column
I know this question may have been already answered elsewhere and apologies for repeating it if so but I haven't found a workable answer as yet. 我知道这个问题可能已经在其他地方回答过了,如果可以的话,很抱歉重复这个问题,但是我还没有找到一个可行的答案。
I have 17 subjects each with two variables as below: 我有17个主题,每个主题都有两个变量,如下所示:
Time (s) OD
130 41.48
130.5 41.41
131 39.6
131.5 39.18
132 39.41
132.5 37.91
133 37.95
133.5 37.15
134 35.5
134.5 36.01
135 35.01
I would like R to identify the first value in column 2 (OD) of my dataframe and create a new column (OD_adjusted) by adding or subtracting (depending if the first value is +ive or -ive) from all values in column 2 so it would look like this: 我想R识别数据框第2列(OD)中的第一个值,并通过从第2列中的所有值相加或减去(取决于第一个值是+ ive或-ive)来创建新列(OD_adjusted),因此它看起来像这样:
Time (s) OD OD_adjusted
130 41.48 0
130.5 41.41 -0.07
131 39.6 -1.88
131.5 39.18 -2.3
132 39.41 -2.07
132.5 37.91 -3.57
133 37.95 -3.53
133.5 37.15 -4.33
134 35.5 -5.98
134.5 36.01 -5.47
135 35.01 -6.47
First value in column 2 is 41.48 therefore I want to subtract this value from all datapoints in column 2 to create a new third column (OD_adjusted). 第2列中的第一个值为41.48,因此我想从第2列中的所有数据点减去此值以创建新的第三列(OD_adjusted)。
I can use OD_adjusted <- ((df$OD) - 41.48)
however, I would like to automate the process using a function and this is where I am stuck: 我可以使用
OD_adjusted <- ((df$OD) - 41.48)
但是,我想使用一个函数来自动化该过程,这就是我遇到的问题:
AUC_OD <- function(df){
return_value_1 = df %>%
arrange(OD) %>%
filter(OD [1,2) %>%
slice_(1)
colnames(return_value_1)[3] <- "OD_adjusted"
if (nrow(return_value_1) > 0 ) { subtract
(return_value_1 [1,2] #into new row
else add
(return_value_1 [1,2] #into new row
}
We get the first element of 'OD' and subtract from the column 我们得到“ OD”的第一个元素并从列中减去
library(dplyr)
df1 %>%
mutate(OD_adjusted = OD- OD[1])
Or using base R
或使用
base R
df1$OD_adjusted <- with(df1, OD - OD[1])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.