[英]Assign observations to a group based on another vector in the same R dataframe
我正在嘗試根據網格正方形ID將區域分配給R中的數據框中的觀察值。 我有以下數據框( df ):
year month square
1 2000 2 A1
2 2000 2 B2
3 2000 2 H5
4 2000 2 J9
5 2000 2 A2
6 2000 3 N8
7 2000 3 M9
8 2000 3 C7
我想為“區域”添加另一列,根據網格正方形將每個觀測值分配給“北部”,“東部”,“南部”或“西部”。 我試過下面的for循環它什么也沒做,
for(i in 1:length(df$square)) {
for(j in 1:length(N)) {
if(df$square[i]==N[j]){
df$area[i]=="N"}
}
}
for(i in 1:length(df$square)) {
if(any(df$square==N)==T){
df$area[i]=="North"}
}
其中“ N”是我創建的對象,其中包含位於北部的正方形,即:
N <- c("A1","A2","B2")
我確實找到了以下相關問題,但是我想知道涉及字符時是否有所不同: 根據R中的另一列分配一個組號
任何幫助,將不勝感激。 謝謝
我建議不要再定義像N
這樣的向量,而是推薦使用第二個data.frame
配對具有面積的正方形:
df <- data.frame(year = 2000,
month = c(2,2,2,2,2,3,3,3),
square = c("A1", "B2", "H5", "J9", "A2", "N8", "M9", "C7"),
stringsAsFactors = FALSE)
areas <- data.frame(square = c("A1", "A2", "B1", "H5", "J9", "M9", "N8"),
area = c("N", "N", "N", "W", "E", "S", "S"),
stringsAsFactors = FALSE)
這樣,只需合並即可:
merge(df, areas, by = "square", all.x = TRUE)
# square year month area
# 1 A1 2000 2 N
# 2 A2 2000 2 N
# 3 B2 2000 2 <NA>
# 4 C7 2000 3 <NA>
# 5 H5 2000 2 W
# 6 J9 2000 2 E
# 7 M9 2000 3 S
# 8 N8 2000 3 S
( NA
的原因是areas
定義不完整。)
d <- data.frame(year = rep(2000, 8), month = rep(3,8),
square = c("A1", "B2", "H5", "J9", "A2", "N8", "M9", "C7"))
N <- c("A1","A2","B2")
for(i in 1:nrow(d)) {
if (d$square[i] %in% N) {
d$area[i] <- "North"
}
else (
d$area[i] <- "Somewhere Else"
)
}
for循環中的else if()語句中的圖層,用於其他基本方向ID向量
在R中,通常最好避免循環,尤其是嵌套循環。 對於這種情況,我更喜歡sapply()
。
N <- c("A1","A2","B2")
#assume these are the other designations
S <- c("H5", "J9")
E <- c("N8","M9")
W <- c("C7")
mydat$area<- sapply(mydat$square, function (x){
if (x %in% N) return("North")
if (x %in% S) return("South")
if (x %in% E) return("East")
if (x %in% W) return("West")
else NA
})
mydat
year month square area
2000 2 A1 North
2000 2 B2 North
2000 2 H5 South
2000 2 J9 South
2000 2 A2 North
2000 3 N8 East
2000 3 M9 East
2000 3 C7 West
當你開始有大型數據集, *apply()
函數會比R.循環更快
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.