1
好了,所以我也有類似的這種結構獲取一列中的另一列的值,R爲1
hashID,value,flag
98fafd, 35, 1
fh56w2, 25, 0
ggjeas, 55, 1
adfh5d, 45, 0
基本上是一個CSV文件中位數是我想要做的就是值列的值,但只包括在計算中的行數flag==1
。
R這有可能嗎?我四處搜尋,並沒有發現任何這樣的事情。
好了,所以我也有類似的這種結構獲取一列中的另一列的值,R爲1
hashID,value,flag
98fafd, 35, 1
fh56w2, 25, 0
ggjeas, 55, 1
adfh5d, 45, 0
基本上是一個CSV文件中位數是我想要做的就是值列的值,但只包括在計算中的行數flag==1
。
R這有可能嗎?我四處搜尋,並沒有發現任何這樣的事情。
這是一個可能性:
閱讀您的數據集使用以下命令:
newdata <- read.csv("stackoverflow questions/mediancol.csv")
# I assume you have the data in csv format
# Showing the data I used for the computation
newdata <- structure(list(hashID = structure(c(1L, 3L, 4L, 2L), .Label = c("98fafd",
"adfh5d", "fh56w2", "ggjeas"), class = "factor"), value = c(35L,
25L, 55L, 45L), flag = c(1L, 0L, 1L, 0L)), .Names = c("hashID",
"value", "flag"), class = "data.frame", row.names = c(NA, -4L
))
> newdata
hashID value flag
1 98fafd 35 1
2 fh56w2 25 0
3 ggjeas 55 1
4 adfh5d 45 0
# Subset the data when flag =1
newdata1 <- subset(newdata,flag==1)
# Look at the summary of the data
> summary(newdata1)
hashID value flag
98fafd:1 Min. :35 Min. :1
adfh5d:0 1st Qu.:40 1st Qu.:1
fh56w2:0 Median :45 Median :1
ggjeas:1 Mean :45 Mean :1
3rd Qu.:50 3rd Qu.:1
Max. :55 Max. :1
# Only look at the median
median(newdata1$value)
[1] 45
您也可以用布爾陣列做在一個快速班輪爲索引的數據框架:
# read the data from a csv file
newdata <- read.csv("file.csv")
# this will give you a vector of boolean values of length nrow(newdata)
newdata$flag==1
# and this line uses the above vector to retrieve only those elements of
# newdata$value for which the row contains a flag value of 1
median(newdata$value[newdata$flag==1])
我建議閱讀一些R的在線常見問題。這是一個非常基本的問題,已經回答了很多次。您正在尋找數據的「子集」。 R中的函數是'['。看看'?'['' – Justin
正如賈斯汀所說,它在R中非常簡單,可能在很多次之前都被問過,但我只是出去嘗試了幾次搜索(僅使用標題中的單詞)並搜索通過「R介紹」並沒有真正成功。這個問題能否成爲下一位提問者的另一個搜索目標? –
其他大多數問題都是關於「mean」,並使用像「subset」,「conditional」或「specific rows」這樣的關鍵詞,所以我在這裏鏈接到它們,因爲它本質上是[the](http://stackoverflow.com/questions/12350783/find-max-mean-min-of-a-subset-in-r)[same](http://stackoverflow.com/questions/12394332/how-to-get-column-mean-for - 僅限特定行/ 12394419)[question](http://stackoverflow.com/questions/12555179/conditional-mean-statement/12587505),但沒有這些條款。 – Thomas