2017-10-31 11 views
0

私は、凝縮された数値の列を含むデータフレームを持っています。Rの文字列の一部を数値に変換するために

final_table.df      ##Dataframe 
final_table.df$insta_followers  ##Column 

それは私は変更する必要があるフォーマットの値の二組含ま:

1)私は000

2.するために「K」を置き換えることができ、このような10Kなどの値) 私が解決しなければならない9.3Kのような値9300

9.3Kなどの値を私の行で9300に置き換えるにはどうすればよいですか?

答えて

0

"strsplit"を使用すると、この問題を解決できます。ここの例

x = "9.3K" 
y = strsplit(x,"[.]") #gives y[[1]][1] = "9" and y[[1]][2] = "3K" 
k = as.numeric(y[[1]][1]) #convert string to float 
d = strsplit(y[[1]][2],"") #gives d[[1]][1]="3" and d[[1]][2]="K" 
d1 = as.numeric(d[[1]][1]) 
number = k*1000 + d1*100 

私はこれがうまくいけば、うまくいきます!

0

私は約3つのソリューションを使い始めましたが、これは最もクリーンでシンプルでわかりやすいと思います。 1 & 2よりも多くのフォーマットがあれば拡張できますが、それらはうまくいくはずです。

df$followers <- ifelse(substr(df$followers, 2, 2)==".", # if second char is "." 
         gsub("K", "00", df$followers), # replace K with 00 
         gsub("K", "000", df$followers)) # else replace K with 000 
df$followers <- as.numeric(df$followers) # convert to numeric at the end 
1

あなたはベクトルからKを削除し、あなたは、あなたがifelse commmandで仕事ができる例92ためKを含まない値を持っている場合は数値変数

x<-c("9.3K","10K") 
substring(x,1,nchar(x)-1) # removes the last character "9.3" "10" 
as.numeric(substring(x,1,nchar(x)-1))*1000 # turn into a numeric and multiply by 1000 
9300 10000 

にそれを回すことができます

as.numeric(ifelse(grepl("K",x),as.numeric(substring(x,1,nchar(x)-1))*1000 ,x)) 

のようなものxが男にK変換が含まれている場合上記以外の場合はx

関連する問題