[英]Altering a data frame in R
我有一個數據框,其第一列從1到365像這樣
c(1,1,1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2,2,2...
第二列的時間像這樣重復一遍又一遍
c(0,30,130,200,230,300,330,400,430,500,0,30,130,200,230,300,330,400,430,500...
因此,對於第一列中的每個1值,我在第二列中都有一個對應的時間,然后當我到達2時,時間重新開始,每個2都有一個對應的時間,
偶爾我會遇到
c(3,3,3,3,3,3,3,3,3,4,4,4,4,4,4,4,4,4,4...
c(0,30,130,200,230,330,400,430,500,0,30,130,200,230,300,330,400,430,500...
這里缺少3的其中之一,並且缺少300的相應時間。
如何遍歷整個數據框並添加這些缺失的值? 我需要一種方法讓R通過並找出所有缺失的值,然后插入一行並將適當的值1到365放入第一列,並在適當的時間放置它。 因此,對於給定的示例,R會在230和330之間添加一行,然后在第一列中放置3,在第二列中放置300。 該列的某些部分缺少幾個連續的值。 不只是這里和那里的一個
編輯:預先明確指定所有10次的解決方案,並進行代碼整理/注釋
您需要創建另一個包含每個可能行的data.frame
,然后merge
其與data.frame
merge
。 關鍵方面是最終合並中的all.x = TRUE
,這會強制突出顯示數據中的差距。 我通過在your.dat
中your.dat
前20種可能的日/時組合中的15種進行了采樣來模擬差距
# create vectors for the days and times
the.days = 1:365
the.times = c(0,30,100,130,200,230,330,400,430,500) # the 10 times to repeat
# create a master data.frame with all the times repeated for each day, taking only the first 20 observations
dat.all = data.frame(x1=rep(the.days, each=10), x2 = rep(the.times,times = 365))[1:20,]
# mimic your data.frame with some gaps in it (only 15 of 20 observations are present)
your.sample = sample(1:20, 15)
your.dat = data.frame(x1=rep(the.days, each=10), x2 = rep(the.times,times = 365), x3 = rnorm(365*10))[your.sample,]
# left outer join merge to include ALL of the master set and all of your matching subset, filling blanks with NA
merge(dat.all, your.dat, all.x = TRUE)
這是合並的輸出,顯示了所有20條可能的記錄,空白清晰可見為NA
:
x1 x2 x3
1 1 0 NA
2 1 30 1.23128294
3 1 100 0.95806838
4 1 130 2.27075361
5 1 200 0.45347199
6 1 230 -1.61945983
7 1 330 NA
8 1 400 -0.98702883
9 1 430 NA
10 1 500 0.09342522
11 2 0 0.44340164
12 2 30 0.61114408
13 2 100 0.94592127
14 2 130 0.48916825
15 2 200 0.48850478
16 2 230 NA
17 2 330 0.52789171
18 2 400 -0.16939587
19 2 430 0.20961745
20 2 500 NA
這里有一些NA處理功能可以幫助您入門。 對於插入任務,您應該使用dput或可復制的示例提供自己的數據。
df <- data.frame(x = sample(c(1, 2, 3, 4), 100, replace = T),
y = sample(c(0,30,130,200,230,300,330,400,430,500), 100, replace = T))
nas <- sample(NA, 20, replace = T)
df[1:20, 1] <- nas
df$y <- ifelse(df$y == 0, NA, df$y)
# Columns x and y have NA's in diferent places.
# Logical test for NA
is.na(df)
# Keep not NA cases of one colum
df[!is.na(df$x),]
df[!is.na(df$y),]
# Returns complete cases on both rows
df[complete.cases(df),]
# Gives the cases that are incomplete.
df[!complete.cases(df),]
# Returns the cases without NAs
na.omit(df)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.