Pouya Khalili
Pouya Khalili

Reputation: 21

how to delete blank cells in r and shift data up?

how to delete blank cells in r and shift data up?

For example:

Flow_X16

2  2000-2  0.105
3  2000-3  0.351
4  2000-4  0.409
5  2000-5  0.914
6  2000-6  1.176
7  2000-7  1.252
8  2000-8  0.774
9  2000-9  0.707
10  2000-10  0.251



14  2001-2  0.006
15  2001-3  0.097
16  2001-4  0.969
17  2001-5  1.469

Upvotes: 1

Views: 537

Answers (2)

GWD
GWD

Reputation: 1464

So under the assumption that you are trying to efficiently import this data I would suggest the awesome data.table::fread() function for such a task, which will basically clean this data up for you with almost minimal to no need for you to adjust any of its default parameters.

df <- data.table::fread(file = 'yourDataFile.txt', header = FALSE, sep = " ")

Upvotes: 0

Ronak Shah
Ronak Shah

Reputation: 388982

We can use rowSums :

df[rowSums(df != '') > 0, ]

#      col1  col2
#2   2000-2 0.105
#3   2000-3 0.351
#4   2000-4 0.409
#5   2000-5 0.914
#6   2000-6 1.176
#7   2000-7 1.252
#8   2000-8 0.774
#9   2000-9 0.707
#10 2000-10 0.251
#14  2001-2 0.006
#15  2001-3 0.097
#16  2001-4 0.969
#17  2001-5 1.469

OR with dplyr

library(dplyr)
df %>%  filter_all(all_vars(. !=""))

data

df <- structure(list(col1 = c("2000-2", "2000-3", "2000-4", "2000-5", 
"2000-6", "2000-7", "2000-8", "2000-9", "2000-10", "", "", "", 
"2001-2", "2001-3", "2001-4", "2001-5"), col2 = c("0.105", "0.351", 
"0.409", "0.914", "1.176", "1.252", "0.774", "0.707", "0.251", 
"", "", "", "0.006", "0.097", "0.969", "1.469")), row.names = c("2", 
"3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", 
"15", "16", "17"), class = "data.frame")

Upvotes: 1

Related Questions