我可以从具有 0 行和 0 列的数据框中创建具有 1 行和 11 列的 tibble 吗?
Can I create a tibble with 1 row and 11 columns in R from a data frame with 0 rows and 0 columns?
我导入了一些 Twitter 数据,这些数据为我提供了一个列表,其中包含每个用户的标题。每个 tibble 有 11 列和不同数量的行,具体取决于 Twitter 用户拥有的列表数量。
如果一个 Twitter 用户没有列表,它会被列为一个 0 行 0 列的数据框(见图中的 [3])。我不想删除此类条目,而是将它们保留为没有列表的用户。
因此,我在考虑是否可以创建一个包含 11 列和 1 行的小标题,其中每个单元格包含一个“99”。
如何将列表中的数据框更改为小标题?
非常感谢您的帮助!
你可以试试:
#get index of dataframes that has 0 columns
inds <- lengths(list_data_outlier) == 0
#get column names from other dataframe which is not empty
cols <- names(list_data_outlier[[which.max(!inds)]])
#create an empty dataframe with data as 99 and 1 row
empty_df <- data.frame(matrix(99, nrow = 1, ncol = length(cols),
dimnames = list(NULL, cols)))
#replace the dataframes with 0 columns with empty_df
list_data_outlier[inds] <- replicate(sum(inds), empty_df, simplify = FALSE)
再次感谢@Ronak Shah!
这很有效:
inds <- lengths(list_data_outlier) == 0
empty_df <- list_data_outlier[[which.max(!inds)]][1, ]
list_data_outlier[inds] <- replicate(sum(inds), empty_df, simplify = FALSE)
但是我没有选择第一行,因此在 DF 中有错误的数据,而是使用了第 50 行:
empty_df <- list_data_outlier[[which.max(!inds)]][50, ]
数量取决于条目数nrows + 1。
这样你会得到一个有 1 行和与列表其余部分相同数量和类型的列的小标题,但不是用“错误”数据填充它而是用 NA 填充,这是我继续分析所需要的.
我导入了一些 Twitter 数据,这些数据为我提供了一个列表,其中包含每个用户的标题。每个 tibble 有 11 列和不同数量的行,具体取决于 Twitter 用户拥有的列表数量。 如果一个 Twitter 用户没有列表,它会被列为一个 0 行 0 列的数据框(见图中的 [3])。我不想删除此类条目,而是将它们保留为没有列表的用户。
因此,我在考虑是否可以创建一个包含 11 列和 1 行的小标题,其中每个单元格包含一个“99”。
如何将列表中的数据框更改为小标题?
非常感谢您的帮助!
你可以试试:
#get index of dataframes that has 0 columns
inds <- lengths(list_data_outlier) == 0
#get column names from other dataframe which is not empty
cols <- names(list_data_outlier[[which.max(!inds)]])
#create an empty dataframe with data as 99 and 1 row
empty_df <- data.frame(matrix(99, nrow = 1, ncol = length(cols),
dimnames = list(NULL, cols)))
#replace the dataframes with 0 columns with empty_df
list_data_outlier[inds] <- replicate(sum(inds), empty_df, simplify = FALSE)
再次感谢@Ronak Shah! 这很有效:
inds <- lengths(list_data_outlier) == 0
empty_df <- list_data_outlier[[which.max(!inds)]][1, ]
list_data_outlier[inds] <- replicate(sum(inds), empty_df, simplify = FALSE)
但是我没有选择第一行,因此在 DF 中有错误的数据,而是使用了第 50 行:
empty_df <- list_data_outlier[[which.max(!inds)]][50, ]
数量取决于条目数nrows + 1。 这样你会得到一个有 1 行和与列表其余部分相同数量和类型的列的小标题,但不是用“错误”数据填充它而是用 NA 填充,这是我继续分析所需要的.