如何在R中的数据集中添加标题?

时间:2012-12-24 12:51:54

标签: r dataset statistics

我需要阅读以下数据文件夹中的''wdbc.data': http://archive.ics.uci.edu/ml/machine-learning-databases/breast-cancer-wisconsin/

使用命令read.csv很容易在R中执行此操作,但由于缺少标题,我该如何添加它?我有这些信息,但不知道该怎么做,我宁愿不编辑数据文件。

5 个答案:

答案 0 :(得分:32)

您可以执行以下操作:

加载数据:

test <- read.csv(
          "http://archive.ics.uci.edu/ml/machine-learning-databases/breast-cancer-wisconsin/breast-cancer-wisconsin.data",
          header=FALSE)

请注意,header的{​​{1}}参数的默认值为read.csv,因此为了获取所有行,您需要将其设置为TRUE

将名称添加到data.frame

中的不同列
FALSE

或者我理解的替代和更快(不重新加载整个数据集):

names(test) <- c("A","B","C","D","E","F","G","H","I","J","K")

答案 1 :(得分:3)

如果您有colnamesdata.frame

,也可以使用matrix代替姓名

答案 2 :(得分:1)

您还可以通过创建值数组并分配该数组来解决此问题:

newheaders <- c("a", "b", "c", ... "x")
colnames(data) <- newheaders

答案 3 :(得分:0)

如果您有兴趣从.txt文件中读取一些数据,并且只将该文件的几列提取到带有定制标头的新.txt文件中,以下代码可能会有用:

# input some data from 2 different .txt files:
civit_gps <- read.csv(file="/path2/gpsFile.csv",head=TRUE,sep=",")
civit_cam <- read.csv(file="/path2/cameraFile.txt",head=TRUE,sep=",")

# assign the name for the output file:
seqName <- "seq1_data.txt"

#=========================================================
# Extract data from imported files
#=========================================================
# From Camera:
frame_idx <- civit_cam$X.frame
qx        <- civit_cam$q.x.rad.
qy        <- civit_cam$q.y.rad.
qz        <- civit_cam$q.z.rad.
qw        <- civit_cam$q.w

# From GPS:
gpsT      <- civit_gps$X.gpsTime.sec.
latitude  <- civit_gps$Latitude.deg.
longitude <- civit_gps$Longitude.deg.
altitude  <- civit_gps$H.Ell.m.
heading   <- civit_gps$Heading.deg.
pitch     <- civit_gps$pitch.deg.
roll      <- civit_gps$roll.deg.
gpsTime_corr <- civit_gps[frame_idx,1]

#=========================================================
# Export new data into the output txt file
#=========================================================
myData <- data.frame(c(gpsTime_corr),
                     c(frame_idx),
                     c(qx),
                     c(qy),
                     c(qz),
                     c(qw))
# Write :
cat("#GPSTime,frameIdx,qx,qy,qz,qw\n", file=seqName)
write.table(myData, file = seqName,row.names=FALSE,col.names=FALSE,append=TRUE,sep = ",")

当然,您应该根据自己的应用程序修改此示例脚本

答案 4 :(得分:0)

这应该可以解决,

      kable(dt) %>%
      kable_styling("striped") %>%
      add_header_above(c(" " = 1, "Group 1" = 2, "Group 2" = 2, "Group 3" = 2))
#OR
kable(dt) %>%
  kable_styling(c("striped", "bordered")) %>%
  add_header_above(c(" ", "Group 1" = 2, "Group 2" = 2, "Group 3" = 2)) %>%
  add_header_above(c(" ", "Group 4" = 4, "Group 5" = 2)) %>%
  add_header_above(c(" ", "Group 6" = 6))

有关更多信息,您可以检查link