将定量变量分配给 R 中数据框中的数据点

Assign quantitative variables to data points in the data frames in R

我正在尝试将数字 1、2 和 3 分配给具有 80 个变量和 250 个观测值(金融时间序列)的数据框。换句话说,我想根据条件将每个数据点分为 1、2 和 3:

我认为有一些 if 功能可以做到这一点。我试图四处寻找这种方法,但我不确定如何正确地表达问题才能得到好的结果。

例如,使用这个构造类似于我的数据框。请注意,向量中的值可以更改。将 dat1 中的值视为 1 到 5 之间的分数。

dat1 = data.frame(
  a = c(2.1,2.3,2.3), 
  b = c(3.6,3.7,3.8), 
  c = c(1.2,1.3,1.4),
  d = c(2.4, 2.3, 3.2), 
  e = c(3.9, 1.2, 3.1))

    a   b   c   d   e
1 2.1 3.6 1.2 2.4 3.9
2 2.3 3.7 1.3 2.3 1.2
3 2.3 3.8 1.4 3.2 3.1

我希望最终结果成为:

dat2=
  a b c d e
1 2 3 1 2 3
2 2 3 1 2 1
3 3 3 1 3 3

如果 dat2 中的数据点具有相同的值,则对 dat1 中的行求和:

dat3=
   X1  X2  X3
1 1.2 4.5 7.5
2 2.5 4.6 3.7
3 1.4 0.0 13.4

有什么办法可以实现吗?我希望这是可以理解的。

你的条件在dat1上基本运行floor。如果您想按行执行此操作,我会先转换为长格式,然后再转换回宽格式。这是一个使用 data.table

的例子
library(data.table)

# convert to data.table and save row id
setDT(dat1)[, id := .I]

# convert to long and the back to wide using the row id and `floor` 
dcast(melt(dat1, id = "id"), # convert to long
      id ~ ifelse(value > 3, 3, floor(value)), # convert back to wide while aggregating
      sum) # calculating sum by group
#    id   1   2    3
# 1:  1 1.2 4.5  7.5
# 2:  2 2.5 4.6  3.7
# 3:  3 1.4 0.0 13.4

在每一列上使用 dplyr inside mutate 中的 case_when()

使用floor获取群组id,我们使用apply

d1=floor(dat1)
d1[d1>3]=3
d1
  a b c d e
1 2 3 1 2 3
2 2 3 1 2 1
3 3 3 1 3 3

xx=cbind(d1,dat1)

bl <- apply(xx,1, function(x){
    aggregate(x[6:10], by=list(Category=x[1:5]), FUN=sum)
})

df=Reduce(function(x, y) merge(x, y, by="Category",all=T), bl)
df$Category=NULL
 t(df)
   [,1] [,2] [,3]
x.x  1.2  4.5  7.5
x.y  2.5  4.6  3.7
x    1.4   NA 13.4