重新调整R

时间:2018-02-08 18:51:05

标签: r loops rescale

我无法理解这个: 假设我有一个数据框:

ID<-c("a","a","b","b","c","c","c","d","d")
count_1<-runif(9)
count_2<-runif(9)
diff<-count_1-count_2
pos<-c(1,1,1,2,2,2,3,3,3)
data<-data.frame(ID,count_1,count_2,diff,pos)
head(data)

  ID   count_1   count_2        diff pos
1  a 0.8822875 0.9180848 -0.03579732   1
2  a 0.3641642 0.4097200 -0.04555586   1
3  b 0.2235055 0.9074667 -0.68396115   1
4  b 0.7228688 0.1091750  0.61369374   2
5  c 0.5627312 0.3356446  0.22708664   2
6  c 0.2036120 0.6002063 -0.39659429   2

我想仅使用函数

重新调整具有特定ID和位置的计数
rescale(data,c(1,10)) #library(scales)

我想将结果写入数据中的额外列y。

data$y<-ifelse(data$pos==1 & data$ID=="a",rescale(data$diff,c(1,10)),
               ifelse(data$position==3 & data$ID=="c",rescale(data$diff,c(1,10)),NA))

这会重新调整数据$ diff中的所有值,而不仅仅是我想根据条件调用的值。

 ID   count_1   count_2        diff pos        y
1  a 0.8822875 0.9180848 -0.03579732   1 4.876081
2  a 0.3641642 0.4097200 -0.04555586   1 4.817724
3  b 0.2235055 0.9074667 -0.68396115   1       NA
4  b 0.7228688 0.1091750  0.61369374   2       NA
5  c 0.5627312 0.3356446  0.22708664   2       NA
6  c 0.2036120 0.6002063 -0.39659429   2       NA

我有什么建议可以获得理想的结果吗?

1 个答案:

答案 0 :(得分:1)

我假设当你说你不想重新调整data$diff中的所有值时,你的意思是你只想重新调整满足你{{1}的特定行}}。即您希望将ifelse()的子集传递给data$diff而不是整列。要做到这一点,你可以这样做:

rescale