簡體   English   中英

在 R 中的 data.frame 中重新縮放選定的數據

[英]rescale selected data in data.frame in R

我無法理解這一點:假設我有一個數據框:

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))

這將重新調整 data$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

任何建議我如何才能獲得所需的結果?

我假設當您說不想重新調整data$diff所有值時,您的意思是您只想重新調整滿足ifelse()的特定行。 即您想傳遞data$diff一個子集來rescale而不是整個列。 為此,您可以執行以下操作:

set.seed(1) #For the earlier data creation

rows <- (data$pos==1 & data$ID=="a") | (data$pos==3 & data$ID=="c")
data[rows, "y"] <- rescale(data[rows,"diff"], c(1,10))

data
#  ID   count_1    count_2        diff pos        y
#1  a 0.2655087 0.06178627  0.20372239   1  2.20415
#2  a 0.3721239 0.20597457  0.16614932   1  1.00000
#3  b 0.5728534 0.17655675  0.39629661   1       NA
#4  b 0.9082078 0.68702285  0.22118494   2       NA
#5  c 0.2016819 0.38410372 -0.18242179   2       NA
#6  c 0.8983897 0.76984142  0.12854826   2       NA
#7  c 0.9446753 0.49769924  0.44697603   3 10.00000
#8  d 0.6607978 0.71761851 -0.05682072   3       NA
#9  d 0.6291140 0.99190609 -0.36279205   3       NA

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM