1

I wanna convert first column into object in R so if the input looks like:

#name of df - KPIF
    namePill KPIPill
1: pill_tech     0.3
2:  pill_EUX     0.2
3:  pill_Bus     0.3

the output should looks like:

#name of df - KPIF
           KPIPill
pill_tech    0.3
pill_EUX     0.2
pill_Bus     0.3

Anyone could help ? Regards, Aleksandra

3 Answers3

1

First create the data frame:

KPIF <- data.frame(namePill=c('pill_tech','pill_EUX','pill_Bus'),
                   KPIPill=c(0.3,0.2,0.3))
KPIF

Then apply the rownames:

> rownames(KPIF) <- KPIF[,'namePill']
> KPIF
           namePill KPIPill
pill_tech pill_tech     0.3
pill_EUX   pill_EUX     0.2
pill_Bus   pill_Bus     0.3

Then drop the unnecessary column, suggesting that your data frame is a larger one having more columns:

> KPIF <- KPIF[!(colnames(KPIF) %in% 'namePill')]
> KPIF
          KPIPill
pill_tech     0.3
pill_EUX      0.2
pill_Bus      0.3
Heikki
  • 2,214
  • 19
  • 34
0

You can just save the vector you want (the KPIPill column) in a new object and assign the other vector (namePill) as names() for the new object:

KPIF <- read.table(text = "    namePill KPIPill
1: pill_tech     0.3
                   2:  pill_EUX     0.2
                   3:  pill_Bus     0.3", header = TRUE)


KPIF_named <- KPIF$KPIPill
names(KPIF_named) <- KPIF$namePill

> KPIF_named
pill_tech  pill_EUX  pill_Bus 
      0.3       0.2       0.3 
LAP
  • 6,605
  • 2
  • 15
  • 28
0

use first rownames()and then you can just get rid off the first column:

I was assuming you made your df like this:

df=as.data.frame(matrix(c('pill_tech','pill_EUX','pill_Bus',0.3,0.2,0.3),3,2))

otherwise you can just convert it to a data frame with as.data.frame(df)

then assign the column namePill to rownames()

rownames(df)=df$namePill

and then you can get rid off the column namePill if it bothers you

df=df[2]

p130ter
  • 86
  • 7