string - R: append a "character" type to a list of numeric values -


i have list of numeric values, say

> list <- c(1,10,12,24) > list [1]  1 10 12 24 

and want append string of characters output reads:

> list [1]  "name" 1 10 12 24 

i tried following code:

list <- c("name",1,10,12,24) 

or

list <- c(1,10,12,24) list <- c("name",as.numeric(list)) 

but, predictably, numerics converted character type:

> list <- c(1,10,12,24) > list <- c("name",as.numeric(list)) > list [1] "name" "1"    "10"   "12"   "24" 

how can preserve numeric type while adding character type in front?

[edit] goal add row existing data frame df df[1] contains strings , df[2:5] contain numerics.

@fernando pretty has idea right: "row" should list if want combine data.frame.

here couple of examples:

## sample `data.frame` mydf <- data.frame(a = c("one", "two"), b = 1:2, c = 3:4,                     d = 5:6, stringsasfactors = false)  ## initial vector... addme <- c(1, 10, 12) ## ... list addme <- c("name", as.list(addme)) addme # [[1]] # [1] "name" #  # [[2]] # [1] 1 #  # [[3]] # [1] 10 # # [[4]] # [1] 12 #  ## put together... new <- rbind(mydf, addme) new #      b  c  d # 1  1 one  3  5 # 2  2 two  4  6 # 3 name 1 10 12 str(new) # 'data.frame':  3 obs. of  4 variables: #  $ a: chr  "one" "two" "name" #  $ b: num  1 2 1 #  $ c: num  3 4 10 #  $ d: num  5 6 12 

alternatively, create 1 row (or more, if necessary) data.frame , bind existing data.frame:

addme <- c(1, 10, 12) rbind(mydf, setnames(cbind("name", data.frame(t(addme))), names(mydf))) #      b  c  d # 1  1 one  3  5 # 2  2 two  4  6 # 3 name 1 10 12  

major note: depends on first column being character, not factor, variable. if factors, need make sure variable contains right levels (or convert character first, re-factor).


Comments

Popular posts from this blog

html - Sizing a high-res image (~8MB) to display entirely in a small div (circular, diameter 100px) -

java - IntelliJ - No such instance method -

identifier - Is it possible for an html5 document to have two ids? -