我在下面有以下数据框。我想将其转换为第二个数据帧。
Currently Have:
CITY0 ST0 Zip0 Lat0 Long0 CITY1 ST1 Zip1 ID Volume
NA NA NA 0.00 0.00 Boston MA 02101 X1 2
Boston MA 02102 42 -71 NA NA NA X1 2
Would like:
CITY0 ST0 Zip0 Lat0 Long0 CITY1 ST1 Zip1 ID Volume
Boston MA 02102 42 -71 Boston MA 02101 X1 2
想要R中的解决方案...谢谢!
答案 0 :(得分:0)
您有两种解决方案:
# df is your data frame
# option 1
df = df[!is.na(df$CITY0),]
# option 2
df = df[complete.cases(df$b),]
答案 1 :(得分:0)
怎么样?
library(tidyverse)
df %>%
mutate_if(is.factor, as.character) %>%
group_by(ID) %>%
mutate_all(function(x) x[!is.na(x) & x != 0]) %>%
slice(1)
## A tibble: 1 x 10
## Groups: ID [1]
# CITY0 ST0 Zip0 Lat0 Long0 CITY1 ST1 Zip1 ID Volume
# <chr> <chr> <int> <dbl> <dbl> <chr> <chr> <int> <chr> <int>
#1 Boston MA 2102 42. -71. Boston MA 2101 X1 2
说明:我们按ID
分组,并用非NA
和非零的条目替换每一列。切片第一行即可折叠。
df <- read.table(text =
"CITY0 ST0 Zip0 Lat0 Long0 CITY1 ST1 Zip1 ID Volume
NA NA NA 0.00 0.00 Boston MA 02101 X1 2
Boston MA 02102 42 -71 NA NA NA X1 2", header = T)