【问题标题】:Exclude column 0 (rownames) column from data frame and csv output从数据框和 csv 输出中排除第 0 列(行名)列
【发布时间】:2015-12-11 15:16:06
【问题描述】:

见鬼去吧,

如何从数据框或 csv 输出中排除零列或行名列?

df <- df[,c(1,2,3,4,5]
drops <- c(0)
df <- df[,!(names(df) %in% drops)]
write.csv(df,'Forecast Values.csv')

我尝试了上述方法,但 rownames 列仍然保留到“df”和 csv 文件中,我特别希望将其排除在 csv 中。另外值得注意的是,变量“drops”的值为零,而不是列为零。

【问题讨论】:

  • R data.frame 中没有“第 0 列”。阅读?write.csv,你会看到一个参数用于包含或不包含row.names

标签: r csv dataframe write.table


【解决方案1】:

您可以删除dataframerownames,只需将它们设置为null。它们默认为空(参见?data.frame),但有时它们会被各种函数设置:

# Create a sample dataframe with row.names
a_data_frame <- data.frame(letters = c("a", "b", "c"), 
                           numbers = c(1, 2, 3), 
                           row.names = c("Row1", "Row2", "Row3"));
# View it
a_data_frame;
>        letters numbers
>Row1       a       1
>Row2       b       2
>Row3       c       3

# Use rownames() to set them to new value, which is null in this case
rownames(a_data_frame) <- NULL;

# View it again
a_data_frame;
>     letters numbers
>1       a       1
>2       b       2
>3       c       3

请注意,NULL rownames 在打印时显示为增量计数,但不再存在于 a_data_frame data frame 对象中,因此当由另一个函数(如 write.csv)处理时,任何 rownames您看到的是由函数创建的,而不是取自 data frame 对象本身。

如上一张海报所述(参见?write.csv),您可以在write.csv 命令中指定row.names=FALSE

【讨论】:

    【解决方案2】:

    您可以像这样将行设置为 NULLrow.names(df) &lt;- NULL

    如果您愿意,还可以重命名行: row.names(df) &lt;- c("row_1","row_2", etc...)

    【讨论】:

      猜你喜欢
      • 2015-07-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-08-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-03
      相关资源
      最近更新 更多