[英]R Transform number/character to be a superscript or subscript
I want to superscript a number (or character, it doesnt matter) to an existing string.我想在现有字符串上标一个数字(或字符,这无关紧要)。
This is what my initial dataframe looks like:这是我最初的 dataframe 的样子:
testframe = as.data.frame(c("A34", "B21", "C64", "D83", "E92", "F24"))
testframe$V2 = c(1,3,2,2,3,NA)
colnames(testframe)[1] = "V1"
V1 V2
1 A34 1
2 B21 3
3 C64 2
4 D83 2
5 E92 3
6 F24 NA
What I want to do now is to use the V2 as a kind of "footnote", so any superscript or subscript (doesnt matter which one).我现在想做的是使用 V2 作为一种“脚注”,所以任何上标或下标(哪个都无关紧要)。 When there is no entry in V2, then I just want to keep V1 as it is.
当V2里面没有entry的时候,那么我只想保持V1原样。
I found a similar question where I saw this answer:我在看到这个答案时发现了一个类似的问题:
> paste0("H", "\u2081", "O")
[1] "H₁O"
This is what I want, but my problem is that it has to be created automatically since I have way too many rows in my real dataframe.这就是我想要的,但我的问题是它必须自动创建,因为我的真实 dataframe 中的行太多了。
I tried to add an extra column "V3" to enter the Superscripts and Subscripts Codes:我试图添加一个额外的列“V3”来输入上标和下标代码:
testframe$V3 = c("u2081", "u2083", "u2082", "u2082", "u2083", NA)
V1 V2 V3
1 A34 1 u2081
2 B21 3 u2083
3 C64 2 u2082
4 D83 2 u2082
5 E92 3 u2083
6 F24 NA <NA>
But when I try paste(testframe$V1, testframe$V3, sep = "\")
it gives me an error.但是当我尝试
paste(testframe$V1, testframe$V3, sep = "\")
时,它给了我一个错误。 How can I use the \ in this case?在这种情况下如何使用 \?
If the subscripts will always be digits 0 through 9, you can index into a vector of Unicode subscript digits:如果下标始终是数字 0 到 9,则可以索引到 Unicode 下标数字的向量中:
subscripts <- c(
"\u2080",
"\u2081",
"\u2082",
"\u2083",
"\u2084",
"\u2085",
"\u2086",
"\u2087",
"\u2089"
)
testframe$V1 <- paste0(
testframe$V1,
ifelse(
is.na(testframe$V2),
"",
subscripts[testframe$V2 + 1]
)
)
testframe
V1 V2
1 A34₁ 1
2 B21₃ 3
3 C64₂ 2
4 D83₂ 2
5 E92₃ 3
6 F24 NA
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.