简体   繁体   中英

Adding one new row and column in r

I want to add a new value to the first column and first row of the data frame.

Sample of data:

  ali ata
1   u   w
2   y   e
3   t   r
4   f   x
5   s   z

Expected Results:

  ali ata
1  ttt  NA
2   u   w
3   y   e
4   t   r
5   f   x
6   s   z

Read the data. Here, it's important to encode strings as strings (not as factors):

df <- read.table(text="ali ata
1   u   w
2   y   e
3   t   r
4   f   x
5   s   z", header = TRUE, stringsAsFactors = FALSE)

You could use rbind to add the value:

rbind(c("ttt", rep(NA, ncol(df) - 1)), df)

   ali  ata
1  ttt <NA>
11   u    w
2    y    e
3    t    r
4    f    x
5    s    z

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM