QNA > H > Come Dividere Una Colonna In R
Domanda

Come dividere una colonna in R

Risposte
03/03/2022
Brandenburg Gallego

Here's my data frame.

  1. > data
  2. Manufacturers
  3. 1 Audi,RS5
  4. 2 BMW,M3
  5. 3 Cadillac,CTS-V
  6. 4 Lexus,ISF

So I would want to split the manufacturers and the models, like this,

  1. > data
  2. Manufacturers Models
  3. 1 Audi RS5
  4. 2 BMW M3
  5. 3 Cadillac CTS-V
  6. 4 Lexus ISF

library(qdap),

colsplit2df(data,, c(Manufacturer, Model), ,)

OR

use separate() by tidyr package

separate(DataTable, ColumnName, into=” “, sep=” ” )

OR

I would like to split one column into two within at data frame based on a delimiter. For example,

  1. a|b
  2. b|c

to become

  1. a b
  2. b c

within a data frame.

  1. df <- data.frame(ID=11:13, FOO=c('a|b', 'b|c', 'x|y'))
  2. separate(data = df, col = FOO, into = c(left, right), sep = \\|)
  3. ID left right
  4. 1 11 a b
  5. 2 12 b c
  6. 3 13 x y

though in this case the defaults are smart enough to work (it looks for non-alphanumeric characters to split on).

OR

  1. separate(data = df, col = FOO, into = c(left, right))
  2. library(reshape2)
  3. before = data.frame(attr = c(1,30,4,6), type=c('foo_and_bar','foo_and_bar_2'))
  4. newColNames <- c(type1, type2)
  5. newCols <- colsplit(before, _and_, newColNames)
  6. after <- cbind(before, newCols)
  7. after <- NULL
  8. after
04/09/2022
Cthrine

Puoi farlo usando la funzione separate() del pacchetto tidyr molto facilmente.

Separate(data,column,into= ,sep= )

Esempio:

Data = exdata

Nome colonna da dividere = Month_Date

separate(exdata,Month_Date,into=c( Month , Date ),sep=_)

Dare una risposta
Perché Savitar vuole uccidere Iris? :: Pratichi il compostaggio interno?
Link utili