简体   繁体   English

从r中的以下行值填充空单元格

[英]Fill Empty cells from the below row values in r

I have data as below 我有如下数据

col1  col2  col3


56    78    89

67     76   43

I want to fill the empty cells as below in r 我想在r中填充如下的空单元格

col1  col2  col3
56    78    89        
56    78    89        
56    78    89
67    76    43    
67    76    43

We need to change the blank cells ( "" ) to NA and then use na.locf from zoo 我们需要将空白单元格( "" )更改为NA ,然后使用zoo na.locf

library(zoo)
df1[] <- lapply(df1, function(x) as.numeric(na.locf(replace(x, x=="", NA), fromLast=TRUE)))
df1
#  col1 col2 col3
#1   56   78   89
#2   56   78   89
#3   56   78   89
#4   67   76   43
#5   67   76   43

data 数据

df1 <- structure(list(col1 = c("", "", "56", "", "67"), col2 = c("", 
 "", "78", "", "76"), col3 = c("", "", "89", "", "43")), .Names = c("col1", 
 "col2", "col3"), row.names = c(NA, -5L), class = "data.frame")

Another solution with fill from tidyr : 用另一种解决方案filltidyr

library(dplyr)
library(tidyr)

df %>%
  mutate_all(as.numeric) %>%
  fill(names(.), .direction = "up") 

Result: 结果:

  col1 col2 col3
1   56   78   89
2   56   78   89
3   56   78   89
4   67   76   43
5   67   76   43

Data: 数据:

df = structure(list(col1 = c("", "", "56", "", "67"), col2 = c("", 
"", "78", "", "76"), col3 = c("", "", "89", "", "43")), .Names = c("col1", 
"col2", "col3"), row.names = c(NA, -5L), class = "data.frame")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 有条件地用不同行的值填充单元格 - Conditionally fill cells with values from different row R移动数据框的单元格以填充空单元格 - R move the cells of a dataframe to fill in empty cells 用 R 中的最后一个非空单元格和下一个非空单元格填充列中两个值之间的空单元格 - Fill empty cells between two values in column with last non empty cell and next non empty cell in R R - 将值从单元格复制到同一列中的空单元格 - R - copy values from cells to empty cells within same columns 使用R,如何基于与列A值的关系用前一行值填充列B中数据框的空白单元格 - Using R, how to fill empty cells of a dataframe in Column B with previous row value based on the relationship with Column A value R数据表:如何在特定单元格的正下方找到未知数量的空单元格,并用编号的字符串填充它们 - R data table : How to find unknown number of empty cells directly below a specific cell and fill them with numbered strings R:高于和低于基准的值填0 - R: Fill in 0 in values that are above and below a benchmark 用 R 中另一列的值替换一列中的空单元格 - Replacing empty cells in a column with values from another column in R 如何在R中同时合并表格并填充空白单元格? - How to merge tables and fill the empty cells in the mean time in R? R用cut()函数合并后填充空单元格 - R Fill in empty cells after binning with cut() function
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM