R 如何在数据框中按行操作数据

R 如何在数据框中按行操作数据,r,dataframe,apply,R,Dataframe,Apply,我有点糊涂了。我在数据框中有这样的数据 index times 1 1 56.60 2 1 150.75 3 1 204.41 4 2 44.71 5 2 98.03 6 2 112.20 我知道指数为1的时间是有偏差的,而指数为1的时间则没有偏差。我需要创建该数据帧的副本,以消除索引为1的样本的偏差。我一直在尝试apply、by和诸如此类的组合。我得到的最接近的是 by(lct, lct$index, f

我有点糊涂了。我在数据框中有这样的数据

    index  times
1       1  56.60
2       1 150.75
3       1 204.41
4       2  44.71
5       2  98.03
6       2 112.20
我知道指数为1的时间是有偏差的,而指数为1的时间则没有偏差。我需要创建该数据帧的副本,以消除索引为1的样本的偏差。我一直在尝试apply、by和诸如此类的组合。我得到的最接近的是

by(lct, lct$index, function(x) { if(x$index == 1) x$times = x$times-50 else x$times = x$times } )

它返回了一个by类的对象,这对我来说是不可用的。我需要将数据以与原始文件相同的格式索引(时间)写入csv文件。想法?

像这样的想法应该行得通:

df$times[df$index ==1] <- df$times[df$times == 1] - 50
并在dplyr中使用它:

那么

index <- c(1, 1, 1, 2, 2, 2)
times <- c(56.60, 150.75, 204.41, 44.71, 98.03, 112.20)
df <- data.frame(index, times)
df$times <- ifelse(df$index == 1, df$times - 50, df$times)


> df
#index  times
#1     1   6.60
#2     1 100.75
#3     1 154.41
#4     2  44.71
#5     2  98.03
#6     2 112.20

所以,若索引为1,你们需要每次减去50,就像那个样。看起来效果不错。您可能需要df$倍[df$index==1]我还添加了一个使用ifelse的解决方案,我认为它更可读。我同意,我希望有类似的东西。直接编写df在这方面如何帮助我?它避免了所有这些$。I@pascal意味着代码更易于阅读,并且包含的多余代码更少。我更喜欢使用dplyr来获得干净的代码,请参见我问题中的示例。
library(dplyr)
df = data.frame(index = sample(1:5, 100, replace = TRUE), 
                value = runif(100)) %>% arrange(index)
df %>% mutate(value = ifelse(index == 1, value - 50, value))
#  index     value
#1     1 -49.95827
#2     1 -49.98104
#3     1 -49.44015
#4     1 -49.37316
#5     1 -49.76286
#6     1 -49.22133
#etc
index <- c(1, 1, 1, 2, 2, 2)
times <- c(56.60, 150.75, 204.41, 44.71, 98.03, 112.20)
df <- data.frame(index, times)
df$times <- ifelse(df$index == 1, df$times - 50, df$times)


> df
#index  times
#1     1   6.60
#2     1 100.75
#3     1 154.41
#4     2  44.71
#5     2  98.03
#6     2 112.20