Fill a column's blank spaces contingent on a second column in R -
i'd appreciate one. have similar data below.
df$a df$b 1 . 1 . 1 . 1 6 2 . 2 . 2 7
what need fill in df$b
each value corresponds end of run of values in df$a
. example below.
df$a df$b 1 6 1 6 1 6 1 6 2 7 2 7 2 7
any welcome.
it seems me missing values denoted .
. better read dataset na.strings="."
missing values na
. current dataset, 'b' column character/factor
class (depending upon whether used stringsasfactors=false/true
(default) in read.table/read.csv
.
using data.table
, convert data.frame
data.table
(setdt(df1)
), change 'character' class 'numeric' (b:= as.numeric(b)
). result in coercing .
na
(a warning appear). grouped "a", change "b" values last element (b:= b[.n]
)
library(data.table) setdt(df1)[,b:= as.numeric(b)][,b:=b[.n] , = a] # b #1: 1 6 #2: 1 6 #3: 1 6 #4: 1 6 #5: 2 7 #6: 2 7 #7: 2 7
or dplyr
library(dplyr) df1 %>% group_by(a) %>% mutate(b= as.numeric(tail(b,1)))
or using ave
base r
df1$b <- with(df1, as.numeric(ave(b, a, fun=function(x) tail(x,1))))
data
df1 <- structure(list(a = c(1l, 1l, 1l, 1l, 2l, 2l, 2l), b = c(".", ".", ".", "6", ".", ".", "7")), .names = c("a", "b"), class = "data.frame", row.names = c(na, -7l))
Comments
Post a Comment