R报错解决:error in rbind(deparse.level, …) : numbers of columns of arguments do not match

自己在处理数据时,遇到了这个报错。
原情况是使用循环从xml文件里读数据,拼接为一个list,list中包括的元素为一行data.frame
但是,每一行的元素是不一样的。使用了

clinical = do.call(rbind,cl) 

然后就找到了这篇blog
https://www.statology.org/error-in-rbinddeparse-level-numbers-of-columns-of-arguments-do-not-match/

How to Fix in R: error in rbind(deparse.level, …) : numbers of columns of arguments do not match

One error you may encounter in R is:

Error in rbind(deparse.level, ...) : 
  numbers of columns of arguments do not match 

This error occurs when you attempt to use the rbind() function in R to row-bind together two or more data frames that do not have the same number of columns.

This tutorial shares exactly how to fix this error.
How to Reproduce the Error

Suppose we have the following two data frames in R:

#create first data frame
df1 <- data.frame(x=c(1, 4, 4, 5, 3),
                  y=c(4, 4, 2, 8, 10))

df1

  x  y
1 1  4
2 4  4
3 4  2
4 5  8
5 3 10

#create second data frame 
df2 <- data.frame(x=c(2, 2, 2, 5, 7),
                  y=c(3, 6, 2, 0, 0),
                  z=c(2, 7, 7, 8, 15))

df2

  x y  z
1 2 3  2
2 2 6  7
3 2 2  7
4 5 0  8
5 7 0 15

Now suppose we attempt to use rbind to row-bind these two data frames into one data frame:

#attempt to row-bind the two data frames together
rbind(df1, df2)

Error in rbind(deparse.level, ...) : 
  numbers of columns of arguments do not match

We receive an error because the two data frames do not have the same number of columns.
How to Fix the Error

There are two ways to fix this problem:

Method 1: Use rbind on Common Columns

One way to fix this problem is to use the intersect() function to find the common column names between the data frames and then row-bind the data frames only on those columns:

#find common column names
common <- intersect(colnames(df1), colnames(df2))

#row-bind only on common column names
df3 <- rbind(df1[common], df2[common])

#view result
df3

   x  y
1  1  4
2  4  4
3  4  2
4  5  8
5  3 10
6  2  3
7  2  6
8  2  2
9  5  0
10 7  0

Method 2: Use bind_rows() from dplyr

Another way to fix this problem is to use the bind_rows() function from the dplyr package, which automatically fills in NA values for column names that do no match:

library(dplyr)

#bind together the two data frames
df3 <- bind_rows(df1, df2)

#view result
df3

   x  y  z
1  1  4 NA
2  4  4 NA
3  4  2 NA
4  5  8 NA
5  3 10 NA
6  2  3  2
7  2  6  7
8  2  2  7
9  5  0  8
10 7  0 15

Notice that NA values are filled in for the values from df1 since column z didn’t exist in this data frame.

library(dplyr)
clinical = do.call(dplyr::bind_rows,cl)

但其实最后我还是没解决,然后发现官网其实有提供整理好的data。frame。。。。。

你可能感兴趣的:(R报错记录,r语言,前端,javascript)